private HttpResponse response;
private HttpClient httpclient = new DefaultHttpClient();
public Map<String,String> getParams(){
Map<String,String> map = new HashMap<String,String>();
String str = getText(loginURL);
String strs1[] = str.split("name=\"struts.token.name\" value=\"");
String strs2[] = strs1[1].split("\" />");
map.put("structs.token.name",strs2[0]);
String strs3[] = str.split("name=\"struts.token\" value=\"");
String strs4[] = strs3[1].split("\" />");
map.put("struts.token",strs4[0]);
return map;
}
private boolean login() {
Map map = getParams();
HttpPost httpost = new HttpPost(loginURL);
// All the parameters post to the web site
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair("loginEmail", userName));
nvps.add(new BasicNameValuePair("loginPassword", password));
nvps.add(new BasicNameValuePair("__checkbox_rememberMe", "true"));
Iterator it = map.keySet().iterator();
while(it.hasNext()) {
String key = it.next().toString();
String value = map.get(key).toString();
nvps.add(new BasicNameValuePair(key, value));
}
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nvps, "UTF-8");//将表单参数转化为“实体”
httpost.setEntity(urlEncodedFormEntity);
response = httpclient.execute(httpost);
HttpEntity entity = response.getEntity();
org.apache.http.Header[] headers = response.getHeaders("Location");
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
httpost.abort();
}
return true;
}
private String getRedirectLocation() {
BufferedHeader locationHeader = (BufferedHeader) response.getFirstHeader("Location");
if (locationHeader == null) {
return null;
}
return locationHeader.getValue();
}
private String getText(String redirectLocation) {
HttpGet httpget = new HttpGet(redirectLocation);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = "";
try {
responseBody = httpclient.execute(httpget, responseHandler);
} catch (Exception e) {
e.printStackTrace();
responseBody = null;
} finally {
httpget.abort();
}
return responseBody;
}
public void printText() {
if (login()) {
System.out.println(getText(redirectURL));
String test = getText(redirectURL);
String redirectLocation = getRedirectLocation();
if (redirectLocation != null) {
System.out.println(getText(redirectLocation));
}
}
}