• HttpClient学习


    最近研究支付接口,用到了HttpClient,特学习下。官网:http://hc.apache.org,先翻译下官网的解释吧,以加深自己对这些概念的理解。

    http组件概览

    The Hyper-Text Transfer Protocol (HTTP) is perhaps the most significant protocol used on the Internet today. Web services, network-enabled appliances and the growth of network computing continue to expand the role of the HTTP protocol beyond user-driven web browsers, while increasing the number of applications that require HTTP support.

    Designed for extension while providing robust support for the base HTTP protocol, the HttpComponents may be of interest to anyone building HTTP-aware client and server applications such as web browsers, web spiders, HTTP proxies, web service transport libraries, or systems that leverage or extend the HTTP protocol for distributed communication.

    HTTP也许是今天在互联网使用中最重要的协议,Web service,可以使用网络的装置以及不断增长的网络计算机继续 扩大HTTP协议的角色,不仅仅用在web浏览器中,同时不断增长的应用也需要http的支持。

    HTTPComponents的设计就是为了扩展以给在http协议基础上提供强大的支持。任何构建类似web浏览器,网络爬虫,http代理,web serice 传输库以及系统等级或者扩展http协议的http客户端和服务端程序的开发者将会喜欢上它。

    HTTP组件结构

    http组件分为HttpComponents Core、HttpComponents Client、HttpComponents AsyncClient、Commons HttpClient (legacy)

    HttpCore is a set of low level HTTP transport components that can be used to build custom client and server side HTTP services with a minimal footprint. HttpCore supports two I/O models: blocking I/O model based on the classic Java I/O and non-blocking, event driven I/O model based on Java NIO.

    The blocking I/O model may be more appropriate for data intensive, low latency scenarios, whereas the non-blocking model may be more appropriate for high latency scenarios where raw data throughput is less important than the ability to handle thousands of simultaneous HTTP connections in a resource efficient manner.

    HTTPCore是一系列的HTTP传输组件,主要用于用最小的空间构建客户端和服务端的HTTP服务。HttpCore 支持两个I/O模块:在java I/O基础上的阻塞I/O和非阻塞甚至驱动基于java NIO的非阻塞I/O

    阻塞I/O对于数据类传输和低延时的脚本的更方便,非阻塞I/O则对于高延时和高并发传输比较方便和有效。

    HttpClient is a HTTP/1.1 compliant HTTP agent implementation based on HttpCore. It also provides reusable components for client-side authentication, HTTP state management, and HTTP connection management. HttpComponents Client is a successor of and replacement for Commons HttpClient 3.x. Users of Commons HttpClient are strongly encouraged to upgrade.

    这个组件是http/1.1在httpCore和HttpClient的基础上遵循http代理的实现,它为客户端验证、HTTP状态管理和HTTP连接管理提供了可重用的组件,成功地替代了Commons HttpClient 3.x,升级吧!!

    Asynch HttpClient is a HTTP/1.1 compliant HTTP agent implementation based on HttpCore NIO and HttpClient components. It is a complementary module to Apache HttpClient intended for special cases where ability to handle a great number of concurrent connections is more important than performance in terms of a raw data throughput.

    这个组件是http/1.1在httpCore NIO和HttpClient components的基础上遵循http代理的实现,它是一个为了解决某些类似高并发的特殊情况补充的组件。

    Commons HttpClient (legacy):Commons HttpClient 3.x codeline is at the end of life. All users of Commons HttpClient 3.x are strongly encouraged to upgrade to HttpClient 4.1.

    这个组件在3.X的时候可以用,4.1已经失效了。

    综上所述:目前最新版的就剩3个组件了。

    3.1的请求封装
    package com.eshore.ismp.pay.common.util;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpException;
    import org.apache.commons.httpclient.NameValuePair;
    import org.apache.commons.httpclient.SimpleHttpConnectionManager;
    import org.apache.commons.httpclient.methods.PostMethod;
    import org.apache.log4j.Logger;
    
    import com.eshore.ismp.pay.common.exception.PayException;
    
    
    public class HttpUtil {
    	protected static final Logger log=Logger.getLogger(HttpUtil.class);
    	public static String postMethod(String url, NameValuePair[] data) throws PayException{
    		if (null == url || url.trim().length() < 1){
    			return null;
    		}
    		PostMethod postMethod = new PostMethod(url);
    		postMethod.setRequestBody(data);
    		HttpClient httpClient = new HttpClient();
    		//连接超时
    		httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
    		//读取超时
    		httpClient.getHttpConnectionManager().getParams().setSoTimeout(40000);
    		try {
    			httpClient.getParams().setBooleanParameter(
    					"http.protocol.expect-continue", false);
    			postMethod.addRequestHeader("Content-Type",
    					"application/x-www-form-urlencoded; charset=" + "gbk");
    			postMethod.addRequestHeader("Connection", "close");
    			int stateCode = httpClient.executeMethod(postMethod);
    			if(stateCode!=200){
    				log.error("响应失败,状态码为:"+stateCode);
    			}
    			InputStream ins = postMethod.getResponseBodyAsStream();
    			BufferedReader br = new BufferedReader(new InputStreamReader(ins,"utf-8"));
    			StringBuffer sbf = new StringBuffer();
    			String line = null;
    			//读数据
    			while ((line = br.readLine()) != null) {
    				sbf.append(line);
    			}
    			br.close();
    			return sbf.toString();
    		} catch (HttpException e) {
    			throw new PayException(PayException.INTERNAL,e.getMessage());
    		} catch (IOException e) {
    			postMethod.releaseConnection();
    			// 考虑长连接关闭方式
    			SimpleHttpConnectionManager connM = (SimpleHttpConnectionManager) httpClient
    					.getHttpConnectionManager();
    			connM.closeIdleConnections(0);
    			throw new PayException(PayException.INTERNAL,e.getMessage());
    		} finally {
    			postMethod.releaseConnection();
    		}
    		
    	}
    
    }
    

     长连接时HttpClient在method.releaseConnection()后并没有把链接关闭,这个方法只是将链接返回给connection manager。如果使用HttpClient client = new HttpClient()实例化一个HttpClient connection manager默认实现是使用SimpleHttpConnectionManager。 

    如何调用这个工具类呢?

    大致如下:

    NameValuePair[] data = {new NameValuePair("cmd", "GetPayBankUrl"),
    				new NameValuePair("para", json.toString())};
    

     

    String returnStr = HttpInterfaceUtil.PostMethod(url, data);
    			System.out.println("returnStr:" + returnStr);
    

      

     

    原生jdk访问
             URL Url = new URL(url);
    		HttpURLConnection UrlCon = (HttpURLConnection) Url.openConnection();
    		UrlCon.setDoOutput(true);
    		UrlCon.setDoInput(true);
    		UrlCon.setConnectTimeout(30000); // 设置连接超时为10s
    		UrlCon.setReadTimeout(30000); // 读取数据超时也是10s
    		UrlCon.setRequestMethod("POST");
    		UrlCon.setUseCaches(false);
    		
    		UrlCon.connect();
    		OutputStreamWriter out = new OutputStreamWriter(UrlCon.getOutputStream());
    		JSONObject json = new JSONObject();
    		String time="20150818152736";
    		String token=MD5.crypt(o2okey+alg+time);
    		System.out.println("TOKEN"+token);
    		json.put("token", token);
    		json.put("time", time);
    		json.put("method", cmd);
    		StringBuffer params=new StringBuffer();
    		params.append("{"orderId":"");
    		params.append(orderId);
    		params.append("","status":"");
    		params.append(status);
    		params.append("","sig":"");
    		params.append(Authenticator).append(""}");
    		json.put("params", params);
    		out.write(URLEncoder.encode(json.toString(), HTTP.UTF_8));
    		out.flush();
    		out.close();
    		BufferedReader reader = new BufferedReader(new InputStreamReader(UrlCon.getInputStream(), "utf-8"));
    		StringBuffer sbf = new StringBuffer();
    		System.out.println(sbf);
    		String line = null;
    		StringBuffer sb = new StringBuffer();
    		while ((line = reader.readLine()) != null) {
    			sb.append(line);
    		}
    		System.out.println("进来了=======" + sb);
    		reader.close();
    		// 断开连接
    		UrlCon.disconnect();
    

    上面的这段用原生代码是传送了一个json字符串

    样式

    XXX

    样式

    XXX

    样式

    XXX

    样式

    XXX

    样式

    XXX

    样式

    XXX

    样式

    XXX

    样式

    XXX

  • 相关阅读:
    .NET面试题目
    ASP.NET应用管理系统框架概述(三)
    ASP.NET应用管理系统框架概述(二)
    ASP.NET应用管理系统框架概述(一)
    InstallShield使用文档
    dotnet的安装包例子
    Access数据库连接池
    InstallShield使用——InstallScript MIS Project例子
    InstallShield使用——例子
    ASP.NET针对Sybase数据库使用分页技术
  • 原文地址:https://www.cnblogs.com/JAYIT/p/4745837.html
Copyright © 2020-2023  润新知