/jPlurk/src/com/googlecode/jplurk/net/StatefulAgent.java

http://jplurk.googlecode.com/ · Java · 242 lines · 198 code · 35 blank · 9 comment · 26 complexity · 818c752d6cb468f21c67557a4c63631c MD5 · raw file

  1. package com.googlecode.jplurk.net;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.HashMap;
  5. import java.util.Iterator;
  6. import java.util.Map;
  7. import java.util.Map.Entry;
  8. import org.apache.commons.httpclient.Cookie;
  9. import org.apache.commons.httpclient.Header;
  10. import org.apache.commons.httpclient.HttpClient;
  11. import org.apache.commons.httpclient.HttpConnection;
  12. import org.apache.commons.httpclient.HttpMethod;
  13. import org.apache.commons.httpclient.HttpState;
  14. import org.apache.commons.httpclient.HttpStatus;
  15. import org.apache.commons.httpclient.UsernamePasswordCredentials;
  16. import org.apache.commons.httpclient.auth.AuthScope;
  17. import org.apache.commons.httpclient.cookie.CookiePolicy;
  18. import org.apache.commons.httpclient.methods.PostMethod;
  19. import org.apache.commons.httpclient.methods.multipart.FilePart;
  20. import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
  21. import org.apache.commons.httpclient.methods.multipart.Part;
  22. import org.apache.commons.httpclient.methods.multipart.StringPart;
  23. import org.apache.commons.httpclient.params.HttpMethodParams;
  24. import org.apache.commons.lang.StringUtils;
  25. import org.apache.commons.logging.Log;
  26. import org.apache.commons.logging.LogFactory;
  27. import com.googlecode.jplurk.Constants;
  28. import com.googlecode.jplurk.model.Account;
  29. public class StatefulAgent {
  30. static Log logger = LogFactory.getLog(StatefulAgent.class);
  31. HttpClient client;
  32. public StatefulAgent() {
  33. client = new HttpClient();
  34. client.getHostConfiguration().setHost(Constants.PLURK_HOST,
  35. Constants.PLURK_PORT, "http");
  36. if(StringUtils.isNotBlank(ProxyProvider.host)){
  37. client.getHostConfiguration().setProxy(ProxyProvider.host, ProxyProvider.port);
  38. }
  39. if (StringUtils.isNotBlank(ProxyProvider.user)) {
  40. HttpState state = new HttpState();
  41. state.setProxyCredentials(
  42. new AuthScope(ProxyProvider.host, ProxyProvider.port),
  43. new UsernamePasswordCredentials(ProxyProvider.user, ProxyProvider.password));
  44. client.setState(state);
  45. }
  46. }
  47. private void activateConnection() {
  48. HttpConnection connection =
  49. client.getHttpConnectionManager().getConnection(client.getHostConfiguration());
  50. if (!connection.isOpen()) {
  51. try {
  52. connection.open();
  53. } catch (IOException e) {
  54. logger.error(e.getMessage(), e);
  55. }
  56. }
  57. }
  58. /**
  59. * Creating the http method and set cookie policy as RFC_2109 (make cookie keep in the http client automatically)
  60. * @param <T>
  61. * @param t
  62. * @param uri
  63. * @return
  64. */
  65. @SuppressWarnings("unchecked")
  66. protected <T extends HttpMethod> T createMethod(Class<T> t, String uri) {
  67. HttpMethod method = null;
  68. try {
  69. method = t.newInstance();
  70. method.setPath(uri);
  71. method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
  72. method.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-TW; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 GTB6 (.NET CLR 3.5.30729)");
  73. } catch (Exception e) {
  74. logger.error(e.getMessage(), e);
  75. }
  76. return (T) method;
  77. }
  78. protected Result followLinkIfNeedded(Map<String, String> params,
  79. PostMethod method, int responseCode) {
  80. if (HttpStatus.SC_MOVED_TEMPORARILY == responseCode) {
  81. Header loc = method.getResponseHeader("Location");
  82. if (loc != null && loc.getValue() != null) {
  83. logger.info("redirect to " + loc.getValue());
  84. return executePost(loc.getValue(), params);
  85. }
  86. }
  87. return null;
  88. }
  89. protected void dumpCookies() {
  90. if (client != null && logger.isDebugEnabled()) {
  91. for (Cookie c : client.getState().getCookies()) {
  92. logger.debug("Cookie: " + c);
  93. }
  94. }
  95. }
  96. protected void dumpResponseHeaders(HttpMethod method) {
  97. if (method != null && logger.isDebugEnabled()) {
  98. logger.debug("uri: " + method.getPath());
  99. for (Header h : method.getResponseHeaders()) {
  100. logger.debug(h.getName() + " : " + h.getValue());
  101. }
  102. }
  103. }
  104. public Result multipartUpload(String uri, File targetFile){
  105. activateConnection();
  106. PostMethod filePost = new PostMethod(uri);
  107. filePost.getParams().setBooleanParameter(
  108. HttpMethodParams.USE_EXPECT_CONTINUE, true);
  109. // filePost.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  110. filePost.setRequestHeader("Referer", "http://www.plurk.com/Shares/showPhoto?mini=0");
  111. Result result = new Result();
  112. try {
  113. Part[] parts = {
  114. new StringPart("mini", "0"),
  115. new FilePart("image", targetFile) };
  116. filePost.setRequestEntity(new MultipartRequestEntity(parts,
  117. filePost.getParams()));
  118. int status = client.executeMethod(filePost);
  119. if (status == HttpStatus.SC_OK) {
  120. result.setOk(true);
  121. try {
  122. result.setResponseBody(filePost.getResponseBodyAsString());
  123. } catch (IOException e) {
  124. logger.error(e.getMessage(), e);
  125. }
  126. } else{
  127. result.setResponseBody(filePost.getResponseBodyAsString());
  128. logger.debug("res:" + status);
  129. }
  130. } catch (Exception e) {
  131. result.setOk(false);
  132. } finally {
  133. filePost.releaseConnection();
  134. }
  135. return result;
  136. }
  137. public Result executePost(String uri, Map<String, String> params) {
  138. activateConnection();
  139. if(logger.isInfoEnabled()){
  140. Map<String, String> _params = new HashMap<String, String>(params);
  141. if(_params.containsKey("password")){
  142. // avoid the user's password logged.
  143. _params.put("password", "****************");
  144. }
  145. logger.info("do method with uri: " + uri + " and params => " + _params);
  146. }
  147. PostMethod method = createMethod(PostMethod.class, uri);
  148. method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  149. Iterator<Entry<String, String>> it = params.entrySet().iterator();
  150. while (it.hasNext()) {
  151. Entry<String, String> e = it.next();
  152. method.addParameter(e.getKey(), e.getValue());
  153. }
  154. int responseCode = 0;
  155. try {
  156. responseCode = client.executeMethod(method);
  157. logger.info("Request Response Code: " + responseCode);
  158. dumpCookies();
  159. dumpResponseHeaders(method);
  160. Result redirect = followLinkIfNeedded(params, method, responseCode);
  161. if (redirect != null) {
  162. method.releaseConnection();
  163. return redirect;
  164. }
  165. if (responseCode != HttpStatus.SC_OK) {
  166. method.releaseConnection();
  167. return Result.FAILURE_RESULT;
  168. }
  169. } catch (Exception e) {
  170. logger.error(e.getMessage(), e);
  171. }
  172. Result result = new Result();
  173. result.setOk(true);
  174. try {
  175. result.setResponseBody(method.getResponseBodyAsString());
  176. } catch (IOException e) {
  177. logger.error(e.getMessage(), e);
  178. } finally {
  179. method.releaseConnection();
  180. }
  181. return result;
  182. }
  183. @SuppressWarnings("serial")
  184. public static void main(String[] args) {
  185. StatefulAgent agent = new StatefulAgent();
  186. final Account account = Account.createWithDynamicProperties();
  187. Result result = null;
  188. result = agent.executePost("/Users/login",
  189. new HashMap<String, String>() {
  190. {
  191. put("nick_name", account.getName());
  192. put("password", account.getPassword());
  193. }
  194. });
  195. System.out.println(result);
  196. result = agent.executePost("/TimeLine/getPlurks",
  197. new HashMap<String, String>() {
  198. {
  199. put("user_id", "3146394");
  200. }
  201. });
  202. System.out.println(result);
  203. agent.executePost("", new HashMap<String, String>());
  204. result = agent.multipartUpload("/Shares/uploadImage", new File("c:/tmp/base.png"));
  205. System.out.println(result);
  206. }
  207. }