HttpClient学习笔记

     HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它很好的支持了 HTTP 协议。Commons-httpclient项目(现在已被移植到jMeter项目中)就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。通过它可以让原来很头疼的事情现在轻松的解决。

 

一,准备环境和jar包

  使用前先到apache官网上下载jar包,网址:http://jmeter.apache.org/download_jmeter.cgi,在项目中导入以下jar包:commons-codec-1.6.jar,commons-httpclient-3.1.jar,commons-logging-1.1.1.jar

 

二,使用步骤

使用 HttpClient 需要以下6个步骤:

1. 创建 HttpClient 的实例

    HttpClient  httpClient = new HttpClient(); 

 

2. 创建某种连接方法(DeleteMethod,EntityEnclosingMethod,ExpectContinueMethod,GetMethod,HeadMethod,MultipartPostMethod,OptionsMethod,PostMethod,PutMethod,TraceMethod)的一个实例,一般可用要目标URL为参数。

    例如:get方式:HttpMethod getMethod=new GetMethod(url);

       post方式:HttpMethod postMethod = new PostMethod(url);

 

3. 调用第一步中创建好的实例的executeMethod方法来执行第二步中创建好的 method 实例.

   httpClient.executeMethod(postMethod);

 

4. 读 response 信息

 

5. 释放连接。(无论执行方法是否成功,都必须释放连接)

   method.releaseConnection();

 

6.对得到的内容进行处理

package com.wxl.test;

import java.io.IOException;
import java.util.Map;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * @author wangxl
 * 
 */
public class HttpClientCenter {

	private static HttpClient httpClient = null;
	// 构造HttpClient的实例
	private static HttpClientCenter instance = null;

	private HttpClientCenter() {
		httpClient = new HttpClient();
	}

	public static HttpClientCenter getInstance() {
		if (instance == null) {
			return new HttpClientCenter();
		}
		return instance;
	}

	/**
	 * GET请求	
	* @param url
	 */
	public void getMethod(String url) {
		GetMethod getMethod = null;
		try {
			URI uri = new URI(url, true);
			getMethod = new GetMethod(url);// 创建GET方法的实例,可同时对请求的头,等等,做相应的设置
			/** 设置代理 */
			HostConfiguration hostConfiguration = new HostConfiguration();
			hostConfiguration.setHost(uri);
			// hostConfiguration.setProxy("127.0.0.1", 8080);// 配置代理IP和端口
			httpClient.setHostConfiguration(hostConfiguration);

			// 使用系统提供的默认的恢复策略
			getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
					new DefaultHttpMethodRetryHandler());

			HttpConnectionManagerParams managerParams = httpClient
					.getHttpConnectionManager().getParams();
			managerParams.setConnectionTimeout(30000); // 设置连接超时时间(单位毫秒)
			managerParams.setSoTimeout(120000); // 设置读数据超时时间(单位毫秒)
			int statusCode = httpClient.executeMethod(getMethod);// 执行getMethod,返回响应码
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: "
						+ getMethod.getStatusLine());
			}
			String charSet = getMethod.getResponseCharSet(); // 响应的字符编码
			byte[] responseBody = getMethod.getResponseBody(); // 读取内容

			System.out.println("responseCode:\r\n" + statusCode);
			System.out.println("charSet:\r\n" + charSet);
			System.out.println("response:\r\n"
					+ new String(responseBody, charSet));
			// 得到相应头信息
			Header headers[] = getMethod.getResponseHeaders();
			System.out.println("headers:");
			for (int i = 0; i < headers.length; i++) {
				System.out.println(headers[i]);
			}
			/**
			 * Date: Thu, 02 Feb 2012 07:15:54 GMT
			 * 
			 * Content-Type: text/vnd.wap.wml;charset=UTF-8
			 * 
			 * Transfer-Encoding: chunked
			 * 
			 * Connection: keep-alive
			 */

		} catch (HttpException e) {
			e.printStackTrace();// 发生致命的异常,可能是协议不对或者返回的内容有问题
		} catch (IOException e) {
			e.printStackTrace();// 发生网络异常
		} finally {
			getMethod.releaseConnection();// 释放连接
		}
	}

	public void postMethod(String url, Map<Object, Object> datas) {
		PostMethod postMethod = new PostMethod(url);
		/** 设置代理---同上GET方法 */
		int params = datas.size();
		NameValuePair[] data = new NameValuePair[params];
		int i = 0;
		for (Object obj : datas.keySet()) {
			data[i++] = new NameValuePair((String) obj, (String) datas.get(obj));
		}
		// NameValuePair[] data = {new NameValuePair("id", "youUserName"), new
		// NameValuePair("passwd", "yourPwd") };//填入各个表单域的值
		// postMethod.setRequestEntity(new
		// StringRequestEntity("createRequestXML()",
		// "text/xml", "GBK")); 可使用XML格式传输post参数
		postMethod.setRequestBody(data);// 将表单的值放入postMethod中
		try {
			HttpConnectionManagerParams managerParams = httpClient
					.getHttpConnectionManager().getParams();
			managerParams.setConnectionTimeout(30000); // 设置连接超时时间(单位毫秒)
			managerParams.setSoTimeout(120000); // 设置读数据超时时间(单位毫秒)
			int statusCode = httpClient.executeMethod(postMethod);// 执行postMethod
			// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
			if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
					|| statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {// 301或者302
				Header locationHeader = postMethod
						.getResponseHeader("location");// 从头中取出转向的地址
				String location = null;
				if (locationHeader != null) {
					location = locationHeader.getValue();
					System.out
							.println("The page was redirected to:" + location);
				} else {
					System.err.println("Location field value is null.");
				}
				return;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void cookieSet() {
		httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);// RFC_2109是支持较普遍的一个,还有其他cookie协议
		HttpState initialState = new HttpState();
		Cookie cookie = new Cookie();
		cookie.setDomain("www.balblabla.com");
		cookie.setPath("/");
		cookie.setName("多情环");
		cookie.setValue("多情即无情");
		initialState.addCookie(cookie);
		httpClient.setState(initialState);
	}

	public void cookieGet() {
		Cookie[] cookies = httpClient.getState().getCookies();
		System.out.println("Present cookies: ");
		for (int i = 0; i < cookies.length; i++) {
			System.out.println(" - " + cookies[i].toExternalForm());
			System.out.println(" - domain=" + cookies[i].getDomain());
			System.out.println(" - path=" + cookies[i].getPath());
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		HttpClientCenter hcc = HttpClientCenter.getInstance();
		String url = "http://www.500wan.com/";
		url = "http://wap.500wan.com";
		hcc.getMethod(url);
		
		// Map<Object, Object> datas = new HashMap<Object, Object>();
		// datas.put("id", "1001");
		// datas.put("pass", "123456");
		// hcc.postMethod(url, datas);

	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值