实现用程序代码来实现某个网站的模拟登录,本文介绍使用httpclient完成这个工作。获得登录后的Session的演示代码如下:
package cn.xiyang.base;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
/**
* 演示登录
* @author xiyang
*
*/
public class Demo3 {
public static void main(String[] args) throws ClientProtocolException, IOException {
HttpClient httpclient = new DefaultHttpClient();
//设置登录参数
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("[user_label]", "sdlgxxy"));
formparams.add(new BasicNameValuePair("[pwd_label]", "*****"));
UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(formparams, "UTF-8");
//新建Http post请求
HttpPost httppost = new HttpPost("http://*****/login");
httppost.setEntity(entity1);
//处理请求,得到响应
HttpResponse response = httpclient.execute(httppost);
String set_cookie = response.getFirstHeader("Set-Cookie").getValue();
//打印Cookie值
System.out.println(set_cookie.substring(0,set_cookie.indexOf(";")));
//打印返回的结果
HttpEntity entity = response.getEntity();
StringBuilder result = new StringBuilder();
if (entity != null) {
InputStream instream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(instream));
String temp = "";
while ((temp = br.readLine()) != null) {
String str = new String(temp.getBytes(), "utf-8");
result.append(str);
}
}
System.out.println(result);
}
}
获得Session之后,把该值保存下来。然后再访问其他受保护对象时设置头信息的Cookie字段就好了,代码片段如下
HttpClient httpclient = new DefaultHttpClient();
// 根据获得的Cookie值,设置头信息,然后发送请求,获得内容
HttpGet httpget = new HttpGet("http://***/showsource?solution_id=7263065");
httpget.setHeader("Cookie", "JSESSIONID=817CF84802016AF09E3DFFE59532FD02");
HttpResponse response = httpclient.execute(httpget);
这样就可以获得该网页的内容。所需的jar包可在附件中下载