昨天写了一篇通过Java程序自动发送文章到百度空间,具体实现原理和代码请参照
今天把那版代码进行了更新,现在可以放置到GAE平台了,这样基于GAE平台环境搭建的个人博客就可以
很方便的将个人的博文同步到百度空间。
具体的实现原理现在不多说了,现在展示一下核心代码:
1. Config.Java
配置个人百度空间的账户名和密码
package com.carey.baidublog;public class Config { public static final String USERNAME = "username"; public static final String PASSWORD = "password";}
2. GAEPublishBaiduActicleServlet.java
用来处理GAE的servlet请求
package com.carey.gae.baidu;import java.io.IOException;import javax.servlet.http.*;import com.carey.baidublog.BDHttpClient;public class GAEPublishBaiduActicleServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { try { BDHttpClient .publishBlog("gae-title", "gae-content", "gae-category"); } catch (Exception e) { e.printStackTrace(); } resp.setContentType("text/plain"); resp.getWriter().println("成功发布一篇博文到百度空间"); }}
3. BDHttpClient.java
完成百度博文的发布
package com.carey.baidublog;import java.net.URL;import java.util.HashMap;import java.util.Set;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.servlet.http.HttpServletResponse;import com.google.appengine.api.urlfetch.HTTPHeader;import com.google.appengine.api.urlfetch.HTTPMethod;import com.google.appengine.api.urlfetch.HTTPRequest;import com.google.appengine.api.urlfetch.HTTPResponse;import com.google.appengine.api.urlfetch.URLFetchService;import com.google.appengine.api.urlfetch.URLFetchServiceFactory;public class BDHttpClient { private static final String LOGIN_URL = "https://passport.baidu.com/?login"; private static final String CREATBLOG_URL = "http://hi.baidu.com/" + Config.USERNAME + "/creat/blog"; private static final String MODIFYCATEGORY_URL = "http://hi.baidu.com/" + Config.USERNAME + "/modify/category/0"; private static final String COMMITBLOG_URL = "http://hi.baidu.com/" + Config.USERNAME + "/commit"; private static final URLFetchService urlFetchService = URLFetchServiceFactory .getURLFetchService(); private static final HashMap globalCookies = new HashMap(); public static void publishBlog(String title, String content, String category) throws Exception { // step 1, login baidu and get cookies String cookies = LoginBaidu(); // step 2, get Bdstoken String bdstoken = getBdstoken(cookies); // step 3, publish article if (bdstoken != null) { postBlog(cookies, bdstoken, title, content, category); } else { throw new Exception("bdstoken == null"); } } private static String LoginBaidu() { HashMap params = new HashMap(); params.put("username", Config.USERNAME); params.put("password", Config.PASSWORD); params.put("pwd", "1"); try { httpPost(null, LOGIN_URL, generateQueryString(params)); } catch (Exception e) { e.printStackTrace(); } return globalCookies.get("set-cookie"); } private static String getBdstoken(String cookies) { try { String res = httpGet(cookies, CREATBLOG_URL, null); Pattern p = Pattern.compile("bdstoken=([0-9a-z]+)\\W"); Matcher m = p.matcher(res); if (m.find()) { return m.group(1); } } catch (Exception e) { e.printStackTrace(); } return null; } private static String createCategory(String cookies, String bdstoken, String category) throws Exception { HashMap params = new HashMap(); // bdstoken params.put("bdstoken", bdstoken); // create category params.put("ct", "2"); params.put("cm", "1"); // Article category, such as "Android", "Google", "默认分类" params.put("spBlogCatName", category); params.put("spRefURL", MODIFYCATEGORY_URL); return httpPost(cookies, COMMITBLOG_URL, generateQueryString(params)); } private static String postBlog(String cookies, String bdstoken, String title, String content, String category) throws Exception { HashMap params = new HashMap(); // bdstoken params.put("bdstoken", bdstoken); // new blog params.put("ct", "1"); params.put("cm", "1"); // add a new article params.put("spBlogID", ""); params.put("edithid", ""); params.put("spBlogCatName_o", ""); // Article title params.put("spBlogTitle", title); // Article content params.put("spBlogText", content); // Article category, such as "Android", "Google", "默认分类" params.put("spBlogCatName", category); // Article view Permissions, // 0 --> every one 1 --> only friend 3 --> only oneself params.put("spBlogPower", "0"); // 0: forbidden comment 1: allow comment params.put("spIsCmtAllow", "1"); // 0: allow share 1: forbidden share params.put("spShareNotAllow", "0"); // verify code params.put("spVcode", ""); params.put("spVerifyKey", ""); // first create category createCategory(cookies, bdstoken, category); return httpPost(cookies, COMMITBLOG_URL, generateQueryString(params)); } private static String generateQueryString(HashMap params) { StringBuffer sb = new StringBuffer(); if (params != null && !params.isEmpty()) { Set keys = params.keySet(); for (String key : keys) { sb.append(key); sb.append("="); sb.append(params.get(key)); sb.append("&"); } // remove last & sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } private static String httpGet(String cookies, String url, String queryString) throws Exception { String ret = null; if (queryString != null && !queryString.equals("")) { url += "?" + queryString; } final HTTPRequest request = new HTTPRequest(new URL(url)); if (cookies != null) { request.setHeader(new HTTPHeader("Cookie", cookies)); } try { final HTTPResponse response = urlFetchService.fetch(request); if (HttpServletResponse.SC_OK != response.getResponseCode()) { System.err.println("HttpGet Method failed: " + response.getResponseCode()); } ret = new String(response.getContent(), "UTF-8"); } catch (Exception e) { throw new Exception(e); } return ret; } private static String httpPost(String cookies, String url, String queryString) throws Exception { String ret = null; final HTTPRequest request = new HTTPRequest(new URL(url), HTTPMethod.POST); request.setHeader(new HTTPHeader("Content-Type", "application/x-www-form-urlencoded")); if (cookies != null) { request.setHeader(new HTTPHeader("Cookie", cookies)); } if (queryString != null && !queryString.equals("")) { request.setPayload(queryString.getBytes("UTF-8")); } try { final HTTPResponse response = urlFetchService.fetch(request); if (HttpServletResponse.SC_OK != response.getResponseCode()) { System.err.println("HttpPost Method failed: " + response.getResponseCode()); } // Get site cookie for (HTTPHeader header : response.getHeaders()) { if (header.getName().equalsIgnoreCase("set-cookie")) { globalCookies.put("set-cookie", header.getValue()); } } ret = new String(response.getContent(), "UTF-8"); } catch (Exception e) { throw new Exception(e); } return ret; }}
以上程序在GAE环境测试通过,运行过程序后会自动在百度空间发布一篇文章,截图如下:
本文是使用 Carey Blog 从 润物无声 进行同步发布的 原文地址: http://www.zhourunsheng.com/articles/2011/06/19/1308448377506.html
没有评论:
发表评论