gravatar

Copy to Blogger Beta

很久以前就開始用 gslin 的 copyblog.pl 把 wordpress feeds 內容複製到 blogger 去,曾經有一段時間是自己改一部份內容直接用 Blogger Atom API 把文章貼進去。後來似乎 API 有所修改或更動,一段時間經常會失敗造成兩邊不同步。現在 Blogger 的帳戶轉換成 Blogger Beta 之後,更是無法使用舊的方式把文章複製過去了。

所以現在改用 Google Data APIs 把內容貼過去。看來看去比較簡單的方法就是參考裡面的 java 範例,直接改一下,搭配上原本的 copyblog.pl 方式。先把文章標題和內容寫到一個檔案,然後執行 java 來透過 Google Client Data Library 把文章內容新增到 Blogger Beta。程式大致如下,


import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.net.URL;
import java.io.*;

class blogpost
{
  final static String email = "user@gmail.com";
  final static String user = "user";
  final static String passwd = "password";
  final static String filename = "content.txt";
  final static String post_url = "http://www.blogger.com/feeds/{BlogId}/posts/default";
  public static void main(String[] args) throws Exception
  {
    File file = new File( filename );
    BufferedReader br = new BufferedReader( new InputStreamReader(
                          new FileInputStream(file), "utf-8"));
    String title = br.readLine();
    String content = "", line = "";
    while( (line = br.readLine()) != null ) {
      content += line;
    }
    br.close();

    URL postUrl = new URL( post_url );
    Entry myEntry = new Entry();

    myEntry.setTitle(new PlainTextConstruct( title ));
    myEntry.setContent(new PlainTextConstruct( content ));

    Person author = new Person( user, null, email );
    myEntry.getAuthors().add(author);

    GoogleService myService = new GoogleService("blogger", "blog-post-1");
    myService.setUserCredentials(email, passwd);

    Entry insertedEntry = myService.insert(postUrl, myEntry);
  }
}