实现用程序代码来实现某个网站的模拟登录,本文介绍使用httpclient完成这个工作。获得登录后的Session的演示,包括 上传图片等
public void login()throws Exception
{
HttpClient httpclient = new DefaultHttpClient();
String url = "http://59.64.131.*:9000/phpwind/mclientapi.php";
//设置登录参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("callback", "user.checkauth"));
params.add(new BasicNameValuePair("params", "[\"admin\",\"21232f297a57a5a743894a0e4a801fc3\"]"));
params.add(new BasicNameValuePair("sign", "4deb6100664f045f2f53a8ed45d3444c"));
//新建Http post请求
// HttpPost httppost = new HttpPost(url);
//httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// HttpResponse response = httpclient.execute(httppost);
//URL 传参,参数构成
String paramString = "?";
for (int i = 0; i < params.size(); i++) {
try {
paramString += params.get(i).getName() + "="
+ URLEncoder.encode(params.get(i).getValue(), "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
paramString += i == params.size() - 1 ? "" : "&";
}
//新建 http get 请求
HttpGet httpget = new HttpGet(url+paramString);
//处理请求,得到响应
HttpResponse response = httpclient.execute(httpget);
//打印head 信息
Header[] headers= response.getAllHeaders();
for(Header header : headers)
System.out.println(header.getName() +"___"+header.getValue());
//得到cookie
String set_cookie = response.getFirstHeader("Set-Cookie").getValue();
//打印Cookie值
System.out.println(set_cookie.substring(0,set_cookie.indexOf(";")));
//打印返回的结果
HttpEntity resEntity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF8"));
String line=null;
System.out.println("Response:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
private void testImageUpload(String localFilename,String url ) throws Exception {
HttpClient client = new DefaultHttpClient();
FileBody file = new FileBody(new File(localFilename));
MultipartEntity entity = new MultipartEntity();
entity.addPart("icon", file);
HttpPost post = new HttpPost(url);
post.setHeader("Cookie", "ce0d5_winduser=BjoBU1cAAFVaAQNXDlJWUAIBAwIGVwQAAFoBBFNXAVdTVA");
post.setEntity(entity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(resEntity.getContent(), "UTF8"));
String line=null;
System.out.println("Response:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
@Test
public void test() throws Exception {
login();
testImageUpload("C:\\2.png","http://59.64.131.*:9000/phpwind/mclientapi.php?callback=user.uploadicon&sign=39159899f1362372e9ba9fe988e53eee");
//testDownload(uid, generateEffectsOne());
//testDownload(uid, generateEffectsTwo(uid));
//testDownload(uid, generateEffectsThree());
}