`

httpclient

 
阅读更多
package com.example.http.httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtils {
	private final Logger logger=LoggerFactory.getLogger(getClass());
	private static HttpConnectionManager connectionManager=null;
    private static int defaultMaxConnPerHost = 30;
    private  static int defaultMaxTotalConn = 80;
    /** 连接超时时间,由bean factory设置,缺省为8秒钟 */
    private static int defaultConnectionTimeout= 8000;
    /** 默认等待HttpConnectionManager返回连接超时(只有在达到最大连接数时起作用):1秒*/
    private static final long defaultHttpConnectionManagerTimeout = 3 * 1000;
	public static HttpConnectionManager getManager(){
		if(connectionManager==null){
			connectionManager = new MultiThreadedHttpConnectionManager();
		    connectionManager.getParams().setDefaultMaxConnectionsPerHost(defaultMaxConnPerHost);
		    connectionManager.getParams().setMaxTotalConnections(defaultMaxTotalConn);
		}
		return connectionManager;
	}

	public String get(String url,String param){
		
		HttpClient client=new HttpClient(getManager());
		client.getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
		client.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
		GetMethod getMethod=new GetMethod(url+"?"+param);
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
		getMethod.getParams().setCredentialCharset("utf-8");
	//	getMethod.setRequestHeader("Connection", "close");
		try {
			int status=client.executeMethod(getMethod);
			if(status==HttpStatus.SC_OK){
			  InputStream input=getMethod.getResponseBodyAsStream();
			  BufferedReader reader=new BufferedReader(new InputStreamReader(input,getMethod.getRequestCharSet()));
			  String tempbf; 
			  StringBuffer html=new StringBuffer(100); 
			  while((tempbf=reader.readLine())!=null){ 
			  html.append(tempbf); 
			  }
			  input.close();
			  return html.toString();
			}else{
				logger.error("http get请求返回的是:"+getMethod.getStatusLine());
				return null;
			}
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			getMethod.releaseConnection();
		}
		
		return null;
	}
	
	public String post(String url,Map<String,String> map){
		String html = "";
		HttpClient httpClient = new HttpClient(getManager());
		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
		httpClient.getParams().setConnectionManagerTimeout(defaultHttpConnectionManagerTimeout);
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader("accept", "*/*");
        postMethod.setRequestHeader("connection", "Keep-Alive");
        postMethod.setRequestHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        postMethod.setRequestHeader("Accept-Language", "zh-cn,zh;q=0.5");
        // postMethod.setRequestHeader("Accept-Encoding", "gzip,deflate");
        // postMethod.setRequestHeader("Content-Type", "text/html;charset=utf-8");
        
        NameValuePair[] data = generatNameValuePair(map);
        // 将表单的值放入postMethod中
        postMethod.setRequestBody(data);
        // 执行postMethod
        try {
			int statusCode = httpClient.executeMethod(postMethod);
			 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
		            // 从头中取出转向的地址
		            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 html;
		        }
			 if(statusCode==HttpStatus.SC_OK){
				    BufferedReader in = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream(), postMethod
			                .getResponseCharSet()));
			        StringBuffer sb = new StringBuffer();
			        int chari;
			        while ((chari = in.read()) != -1) {
			            sb.append((char) chari);
			        }
			        html = sb.toString();
			        in.close();
			        return html;
			 }
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			postMethod.releaseConnection();
		}
      
      return null;
	}
	
	protected   static NameValuePair[] generatNameValuePair(Map<String, String> map) {
        NameValuePair[] nameValuePair = new NameValuePair[map.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue());
        }

        return nameValuePair;
    }
}

分享到:
评论

相关推荐

    httpclient.jar包下载

    《深入解析httpclient.jar及其与code.jar的关联》 在Java开发中,HTTP通信是不可或缺的一部分,而Apache HttpClient库正是Java实现HTTP客户端操作的重要工具。本文将深入探讨httpclient.jar包,以及它与code.jar包...

    HttpClient4.2.1版本的Jar包

    HttpClient 4.2.1版本引入了一些重要的改进和修复,以提高性能和稳定性。以下是一些关键特性: 1. **连接管理**:HttpClient 4.2.1引入了更完善的连接管理机制,允许开发者控制连接的创建、复用和关闭。`...

    HttpClient 3.x to HttpComponents HttpClient 4.x

    例如,在HttpClient 3.x中,代码可能会使用`***mons.httpclient.HttpClient`类和`***mons.httpclient.methods.GetMethod`等,而在4.x版本中,这些都被新的API所替代。程序员需要熟悉`org.apache....

    httpclient4.2.1.zip

    本文将深入探讨HttpClient 4.2.1的核心特性和使用方法,帮助开发者更好地理解和应用这个强大的工具。 一、HttpClient简介 HttpClient是一个开放源码的Java库,由Apache软件基金会维护。它为Java程序员提供了一个...

    httpClient

    HttpClient httpClient = new HttpClient(); // 设置 Http 连接超时为5秒 httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000); /* 2 生成 GetMethod 对象并设置参数 */ GetMethod ...

    httpclient方式调用url

    本篇文章将深入探讨如何使用HttpClient方式调用URL,以及相关的知识点。 首先,HttpClient允许我们构建复杂的HTTP请求,包括GET、POST以及其他HTTP方法。使用HttpClient调用URL的基本步骤包括创建HttpClient实例、...

    httpclient-4.5.6-API文档-中文版.zip

    赠送jar包:httpclient-4.5.6.jar; 赠送原API文档:httpclient-4.5.6-javadoc.jar; 赠送源代码:httpclient-4.5.6-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.6.pom; 包含翻译后的API文档:httpclient...

    HttpClientHelper 工具类

    HttpClientHelper 对这个类进行了封装,使得开发者无需直接与HttpClient接口打交道,而是通过更简洁、易用的方法调用来实现网络通信。这提高了代码的可读性和可维护性。 单例模式是软件设计模式的一种,确保一个类...

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    这个实例主要涉及如何配置HttpClient来忽略SSL(Secure Socket Layer)验证,这对于在开发和测试环境中处理自签名证书或未认证的服务器非常有用。以下将详细介绍HttpClient的使用以及如何进行SSL验证的忽略。 首先...

    httpClient需要的jar包

    本压缩包文件"httpClient"很可能包含了HttpClient库所需的必备JAR文件,这些文件通常包括HttpClient的核心库、依赖的第三方库以及可能的扩展模块。为了正确使用HttpClient,你需要确保将这些JAR文件添加到你的项目类...

    HttpClient 调用WebService示例

    在本文中,我们将深入探讨如何使用HttpClient调用WebService。 首先,调用WebService通常涉及SOAP(Simple Object Access Protocol)或RESTful API。HttpClient可以处理这两种类型的Web服务。在本示例中,我们假设...

    httpClient组合包.zip

    此外,HttpClient还支持异步操作,可以在多线程环境中高效地处理并发请求。 2. **httpcore-4.4.12.jar**:这是HttpClient的核心库,包含了HTTP协议的基本组件,如连接管理、请求和响应模型、编码器和解码器等。...

    HttpClient所需jar包(全) httpClient.4.13jar

    HttpClient 4.13版本是这个库的一个较新版本,包含了一系列的改进和修复。 在Java开发中,HttpClient是一个常用的工具,尤其在处理Web服务或者API调用时。它支持同步和异步操作,可以处理复杂的HTTP协议细节,使...

    httpclient-4.5.5-API文档-中文版.zip

    赠送jar包:httpclient-4.5.5.jar; 赠送原API文档:httpclient-4.5.5-javadoc.jar; 赠送源代码:httpclient-4.5.5-sources.jar; 包含翻译后的API文档:httpclient-4.5.5-javadoc-API文档-中文(简体)版.zip ...

    HTTPClient 的一个封装

    这个“HTTPClient的一个封装”显然指的是对Apache HttpClient库进行了定制化处理,以适应特定项目需求或者简化API使用。下面将详细讨论HttpClient的核心概念、封装的目的以及可能实现的方式。 HttpClient是Apache...

    httpclient-4.5.13-API文档-中英对照版.zip

    赠送jar包:httpclient-4.5.13.jar; 赠送原API文档:httpclient-4.5.13-javadoc.jar; 赠送源代码:httpclient-4.5.13-sources.jar; 赠送Maven依赖信息文件:httpclient-4.5.13.pom; 包含翻译后的API文档:...

    HTTPClient

    ### HTTPClient知识点详解 #### 1. HttpClient4 – 获取状态码 **1.1 概览** 本节将详细介绍如何使用HttpClient 4.x版本来获取HTTP响应的状态码,并对其进行验证。这对于开发人员来说是一个非常实用的功能,可以...

    Java HttpClient 全部的jar包

    在Java项目中,使用HttpClient可以实现与Web服务器的高效通信。下面将详细介绍这12个jar包的作用及其在HttpClient中的功能: 1. `commons-beanutils-1.8.0.jar`: Apache Commons BeanUtils库提供了对Java Beans属性...

    使用HttpClient必须的jar包

    这些jar包包含了HttpClient的核心组件、依赖库和其他必要的工具,它们共同构成了HttpClient的运行环境。 以下是一些关键的HttpClient相关的知识点: 1. **HttpClient核心组件**:HttpClient的核心库`httpclient-x....

Global site tag (gtag.js) - Google Analytics