使用HttpClient组件进行网站的模拟登录

实现用程序代码来实现某个网站的模拟登录,本文介绍使用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包可在附件中下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值