JavaライブラリのGoogle Data Java Client Library1.47.1のBloggerのAPIを使用し、Blogの投稿を下書きで作成します。
【手順】
1.「Javaプロジェクトの作成方法」の手順で、「BloggerSample001-Login」といプロジェクトを作成。
2.「Google Data Java Client Library1.47.1の必須jarファイルをライブラリに設定する方法(Javaプロジェクト)」の手順で、Google Data Java Client Library1.47.1の必須jarファイルをライブラリに設定します。
3.「Google Data Java Client Library1.47.1の依存jarファイルをライブラリに設定する方法(Javaプロジェクト)」の手順で、Google Data Java Client Library1.47.1の依存jarファイルをライブラリに設定します。
4.「Google Data Java Client Library1.47.1のBloggerのjarファイルをライブラリに設定する方法(Javaプロジェクト)」の手順で、Google Data Java Client Library1.47.1のBloggerのjarファイルをライブラリに設定します。
5.「Main.java」を以下の様に入力。
import java.io.IOException; import java.net.URL; import com.google.gdata.client.GoogleService; import com.google.gdata.data.Entry; import com.google.gdata.data.Feed; import com.google.gdata.data.PlainTextConstruct; import com.google.gdata.util.AuthenticationException; import com.google.gdata.util.ServiceException; public class Main { public static void main(String[] args) { GoogleService myService = new GoogleService("blogger", "foolprogrammer-SampleClient"); try { myService.setUserCredentials("foolprogrammer@gmail.com", "xxx"); System.out.println("ログインに成功しました。"); } catch (AuthenticationException e) { System.out.println("ログインに失敗しました。"); e.printStackTrace(); return; } try { createPost(myService, getBlogId(myService), "記事のタイトル", "この記事はプログラムから投稿されました。", true); } catch (ServiceException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static String getBlogId(GoogleService myService) throws ServiceException, IOException { // Get the metafeed final URL feedUrl = new URL( "http://www.blogger.com/feeds/default/blogs"); Feed resultFeed = myService.getFeed(feedUrl, Feed.class); // If the user has a blog then return the id (which comes after 'blog-') if (resultFeed.getEntries().size() > 0) { Entry entry = resultFeed.getEntries().get(0); return entry.getId().split("blog-")[1]; } throw new IOException("User has no blogs!"); } public static Entry createPost(GoogleService myService, String blogId, String title, String content, Boolean isDraft) throws ServiceException, IOException { // Create the entry to insert Entry myEntry = new Entry(); myEntry.setTitle(new PlainTextConstruct(title)); myEntry.setContent(new PlainTextConstruct(content)); myEntry.setDraft(isDraft); // Ask the service to insert the new entry URL postUrl = new URL("http://www.blogger.com/feeds/" + blogId + "/posts/default"); return myService.insert(postUrl, myEntry); } }
6.「Ctrl+Shift+O」を押し、Import文を補完、「Ctrl+Shift+F」を押し、ソースコードをフォーマッティング、「Ctrl+S」でファイルを保存。
7.「Javaプロジェクトの実行方法」の手順で、「Main.java」を実行。
8.以下の様に表示されれば成功です。
以上です。
0 件のコメント:
コメントを投稿
注: コメントを投稿できるのは、このブログのメンバーだけです。