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