现在的位置: 首页 > 云计算> 正文
通过GAE平台自动发布文章到百度空间
2011年07月02日 云计算 暂无评论 ⁄ 被围观 2,442+

昨天写了一篇通过Java程序自动发送文章到百度空间,具体实现原理和代码请参照<<Java程序自动发布文章到百度空间>>

今天把那版代码进行了更新,现在可以放置到GAE平台了,这样基于GAE平台环境搭建的个人博客就可以

很方便的将个人的博文同步到百度空间。

具体的实现原理现在不多说了,现在展示一下核心代码:

1. Config.Java

配置个人百度空间的账户名和密码

1
2
3
4
5
6
package com.carey.baidublog;  
 
public class Config {    
 public static final String USERNAME = "username";    
 public static final String PASSWORD = "password";
}
package com.carey.baidublog;  

public class Config {    
 public static final String USERNAME = "username";    
 public static final String PASSWORD = "password";
}

2. GAEPublishBaiduActicleServlet.java

用来处理GAE的servlet请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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("成功发布一篇博文到百度空间");    
 }
}
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

完成百度博文的发布

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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 = "<a href="https://passport.baidu.com/?login">https://passport.baidu.com/?login</a>";    
 private static final String CREATBLOG_URL = "<a href="http://hi.baidu.com/">http://hi.baidu.com/</a>" + Config.USERNAME + "/creat/blog";    
 private static final String MODIFYCATEGORY_URL = "<a href="http://hi.baidu.com/">http://hi.baidu.com/</a>" + Config.USERNAME + "/modify/category/0";    
 private static final String COMMITBLOG_URL = "<a href="http://hi.baidu.com/">http://hi.baidu.com/</a>" + 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;    
 }
}
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 = "<a href="https://passport.baidu.com/?login">https://passport.baidu.com/?login</a>";    
 private static final String CREATBLOG_URL = "<a href="http://hi.baidu.com/">http://hi.baidu.com/</a>" + Config.USERNAME + "/creat/blog";    
 private static final String MODIFYCATEGORY_URL = "<a href="http://hi.baidu.com/">http://hi.baidu.com/</a>" + Config.USERNAME + "/modify/category/0";    
 private static final String COMMITBLOG_URL = "<a href="http://hi.baidu.com/">http://hi.baidu.com/</a>" + 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环境测试通过,运行过程序后会自动在百度空间发布一篇文章,截图如下:

给我留言

留言无头像?


×
腾讯微博