package main; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.SocketTimeoutException; import java.net.URLEncoder; import java.nio.charset.CodingErrorAction; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import org.apache.http.Consts; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.MessageConstraints; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.config.SocketConfig; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContextBuilder; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * HTTP协议请求 * @author admin * */ public final class HTTPUtil { private final static Logger logger = LoggerFactory.getLogger(HTTPUtility.class); private static final int REQUEST_TIMEOUT = 30 * 1000; // 设置请求超时10秒钟 private static final int TIMEOUT = 60 * 1000; // 连接超时时间 private static final int SO_TIMEOUT = 60 * 1000; // 数据传输超时 private static final String CHARSET = "UTF-8"; private static PoolingHttpClientConnectionManager connManager = null; private static CloseableHttpClient httpClient = null; static { try { // SSLContext SSLContextBuilder sslContextbuilder = new SSLContextBuilder(); sslContextbuilder.useTLS(); SSLContext sslContext = sslContextbuilder.loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)).build(); // Create ConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); // Create socket configuration SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build(); connManager.setDefaultSocketConfig(socketConfig); // Create message constraints MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build(); // Create connection configuration ConnectionConfig connectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE) .setCharset(Consts.UTF_8) .setMessageConstraints(messageConstraints).build(); connManager.setDefaultConnectionConfig(connectionConfig); connManager.setMaxTotal(200); connManager.setDefaultMaxPerRoute(20); // Create httpClient httpClient = HttpClients.custom().disableRedirectHandling().setConnectionManager(connManager).build(); } catch (KeyManagementException e) { logger.error("KeyManagementException", e); } catch (NoSuchAlgorithmException e) { logger.error("NoSuchAlgorithmException", e); } catch (Exception e) { e.printStackTrace(); } } /** * 指定参数名GET方式请求数据 * @param url * @param paramsMap QueryString * @return */ public static String doGet(String url, Map<String, String> paramsMap) { return doGet(invokeUrl(url, paramsMap)); } /** * GET方式请求数据 * @param url */ public static String doGet(String url) { HttpGet httpGet = new HttpGet(url); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SO_TIMEOUT) .setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(REQUEST_TIMEOUT).build(); httpGet.setConfig(requestConfig); long responseLength = 0; // 响应长度 String responseContent = null; // 响应内容 String strRep = null; try { // 执行get请求 HttpResponse httpResponse = httpClient.execute(httpGet); // 头信息 printHeaders(httpResponse); // 获取响应消息实体 HttpEntity entity = httpResponse.getEntity(); if (entity != null) { responseLength = entity.getContentLength(); responseContent = EntityUtils.toString(entity, CHARSET);//不能重复调用此方法,IO流已关闭。 System.err.println("内容编码: " + entity.getContentEncoding()); System.err.println("请求地址: " + httpGet.getURI()); System.err.println("响应状态: " + httpResponse.getStatusLine()); System.err.println("响应长度: " + responseLength); System.err.println("响应内容: \r\n" + responseContent); // 获取HTTP响应的状态码 int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { strRep = responseContent; // EntityUtils.toString(httpResponse.getEntity()); } // Consume response content EntityUtils.consume(entity); // Do not need the rest httpGet.abort(); } } catch (ClientProtocolException e) { logger.error("ClientProtocolException", e); e.printStackTrace(); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException", e); e.printStackTrace(); } catch (ConnectTimeoutException e) { logger.error("ConnectTimeoutException", e); e.printStackTrace(); } catch (SocketTimeoutException e) { logger.error("SocketTimeoutException", e); e.printStackTrace(); } catch (Exception e) { logger.error("Exception", e); } finally { httpGet.releaseConnection(); } return strRep; } /** * 不指定参数名的方式来POST数据 * @param url * @param jsonXMLString * @return */ public static String doPost(String url, String jsonXMLString) { return doPost(url, null, jsonXMLString); } /** * 指定参数名POST方式请求数据 * @param url */ public static String doPost(String url, Map<String, String> paramsMap) { return doPost(url, paramsMap, null); } private static String doPost(String url, Map<String, String> paramsMap, String jsonXMLString) { HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-type", "text/xml; charset=gbk"); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SO_TIMEOUT) .setConnectTimeout(TIMEOUT) .setConnectionRequestTimeout(REQUEST_TIMEOUT) .setExpectContinueEnabled(false).build(); httpPost.setConfig(requestConfig);// RequestConfig.DEFAULT long responseLength = 0; // 响应长度 String responseContent = null; // 响应内容 String strRep = null; try { if(paramsMap !=null && jsonXMLString == null) { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(getParamsList(paramsMap), CHARSET); httpPost.setEntity(entity); } else { httpPost.setEntity(new StringEntity(jsonXMLString, CHARSET)); } // 执行post请求 HttpResponse httpResponse = httpClient.execute(httpPost); // 头信息 printHeaders(httpResponse); // 获取响应消息实体 HttpEntity entityRep = httpResponse.getEntity(); if (entityRep != null) { responseLength = entityRep.getContentLength(); responseContent = EntityUtils.toString(httpResponse.getEntity(), CHARSET); // byte[] bytes = EntityUtils.toByteArray(entityRep); System.err.println("内容编码: " + entityRep.getContentEncoding()); System.err.println("请求地址: " + httpPost.getURI()); System.err.println("响应状态: " + httpResponse.getStatusLine()); System.err.println("响应长度: " + responseLength); System.err.println("响应内容: \r\n" + responseContent); // 获取HTTP响应的状态码 int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { strRep = responseContent; // EntityUtils.toString(httpResponse.getEntity()); // 格式化输出XML System.err.println("-----------------------------------------"); System.err.println(formatXML(responseContent)); System.err.println("-----------------------------------------"); } else if ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY) || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER) || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT)) { // 重定向处理,获得跳转的网址 Header locationHeader = httpResponse.getFirstHeader("Location"); if(locationHeader != null) { String successUrl = locationHeader.getValue(); System.out.println(successUrl); } } // Consume response content EntityUtils.consume(entityRep); // Do not need the rest httpPost.abort(); } } catch (ClientProtocolException e) { logger.error("ClientProtocolException", e); e.printStackTrace(); } catch (UnsupportedEncodingException e) { logger.error("UnsupportedEncodingException", e); e.printStackTrace(); } catch (ConnectTimeoutException e) { logger.error("ConnectTimeoutException", e); e.printStackTrace(); } catch (SocketTimeoutException e) { logger.error("SocketTimeoutException", e); e.printStackTrace(); } catch (Exception e) { logger.error("Exception", e); e.printStackTrace(); } finally { httpPost.releaseConnection(); // try // { // httpClient.close(); // } // catch (IOException e) // { // e.printStackTrace(); // } } return strRep; } // 打印头信息 private static void printHeaders(HttpResponse httpResponse) { System.out.println("------------------------------"); // 头信息 HeaderIterator it = httpResponse.headerIterator(); while (it.hasNext()) { System.out.println(it.next()); } System.out.println("------------------------------"); } // 读取内容 protected static String readContent(InputStream in) throws Exception { BufferedInputStream buffer = new BufferedInputStream(in); StringBuilder builder = new StringBuilder(); byte[] bytes = new byte[1024]; int line = 0; while ((line = buffer.read(bytes)) != -1) { builder.append(new String(bytes, 0, line, CHARSET)); } return builder.toString(); } /** * GET方式传参 * @param url * @param paramsMap * @return */ public static String invokeUrl(String url, Map<String, String> paramsMap) { StringBuilder sb = new StringBuilder(); sb.append(url); int i = 0; if(paramsMap != null && paramsMap.size()>0) { for (Map.Entry<String, String> entry : paramsMap.entrySet()) { if (i == 0 && !url.contains("?")) { sb.append("?"); } else { sb.append("&"); } sb.append(entry.getKey()); sb.append("="); String value = entry.getValue(); try { sb.append(URLEncoder.encode(value, CHARSET)); } catch (UnsupportedEncodingException e) { logger.warn("encode http get params error, value is " + value, e); try { sb.append(URLEncoder.encode(value, null)); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } } i++; } } return sb.toString(); } /** * 将传入的键/值对参数转换为NameValuePair参数集 * * @param paramsMap 参数集, 键/值对 * @return NameValuePair参数集 */ private static List<NameValuePair> getParamsList(Map<String, String> paramsMap) { if (paramsMap == null || paramsMap.size() == 0) { return null; } // 创建参数队列 List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> map : paramsMap.entrySet()) { params.add(new BasicNameValuePair(map.getKey(), map.getValue())); } return params; } /** * 格式化XML * @param inputXML * @return * @throws Exception */ public static String formatXML(String inputXML) throws Exception { Document doc = DocumentHelper.parseText(inputXML); StringWriter out = null; if(doc != null) { try { OutputFormat format = OutputFormat.createPrettyPrint(); out = new StringWriter(); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { out.close(); } return out.toString(); } return inputXML; } }
相关推荐
本教程将介绍HttpClient的基本概念和使用方法。 首先,HttpClient的核心功能是执行HTTP请求。通过创建HttpClient实例和指定的HTTP方法对象(如HttpGet、HttpPost等),可以向目标服务器发起请求并获取响应。以下是...
例如,在HttpClient 3.x中,代码可能会使用`***mons.httpclient.HttpClient`类和`***mons.httpclient.methods.GetMethod`等,而在4.x版本中,这些都被新的API所替代。程序员需要熟悉`org.apache....
首先,`httpclient4中文API.pdf`是HttpClient 4.5的中文版API文档,是学习和使用HttpClient的重要参考资料。这个文档通常会包含HttpClient的类结构、接口、方法等详细信息,以及如何使用这些API来构建HTTP请求的示例...
- HttpClient 4支持异步操作,使用`HttpAsyncClient`,可以实现非阻塞的请求/响应处理。 - 异步请求的回调可以通过`Future<HttpResponse>`和` HttpContext`来处理。 6. **重试策略和异常处理**: - 可以配置重试...
在本文中,我们将深入探讨HttpClient 4的关键特性、使用方法以及常见应用场景。 1. **基本概念** - **HttpClient**:HttpClient 是一个实现了HTTP协议的客户端编程工具包,支持HTTP/1.0和HTTP/1.1协议,同时具备...
HttpClient 4 版本引入了许多改进,使得文件上传变得更加简单和高效。在这个主题中,我们将深入探讨HttpClient 4如何实现文件上传,以及相关的核心概念和技术。 首先,我们需要了解HttpClient 4的基本用法。...
2013-11-21 15:31 292,890 httpclient-4.0.2.jar 2017-12-20 12:08 351,132 httpclient-4.1.1.jar 2012-08-03 01:45 451,595 httpclient-4.1.2-sources.jar 2012-08-03 01:44 352,254 httpclient-4.1.2.jar 2012-08-...
在描述中提到的“httpclient4”,指的是HttpClient 4.x系列,这是一个稳定且广泛使用的版本。 在HttpClient 4.4.1.jar中,包含了HttpClient的主要功能实现,如HTTP方法(GET, POST等)、连接管理、重定向处理、身份...
本文档将详细介绍如何使用HttpClient 4.x版本实现文件上传功能。 #### 二、核心类与接口介绍 1. **HttpClient**: - `HttpClient`是Apache HttpClient提供的核心接口,用于执行HTTP请求并获取响应。 - 在本例中...
这篇博客通过实例展示了如何使用HttpClient4模拟登录并进行回贴操作,这对于理解HttpClient4的使用方法及其在网络编程中的应用非常有帮助。如果想要深入学习,可以参考官方文档和相关教程,以更好地掌握HttpClient4...
本教程将基于标题"HTTPClient简单使用"和提供的文件`HttpService`、`HttpClient`来阐述HTTPClient的基本使用方法。 1. **HTTPClient简介** HTTPClient是Apache的 HttpClient库,它为Java开发者提供了全面的HTTP...
同时,注意HttpClient库已经不再更新,对于新的Java项目,推荐使用现代化的HTTP客户端库,如Apache HttpClient的后继者Apache HTTP Components HttpClient 4.x系列,或者使用Java标准库的`java.net.http.HttpClient`...
《深入剖析HTTPClient4源码》 HTTPClient4是Apache软件基金会开发的一个强大的HTTP客户端库,广泛应用于Java编程中,提供了高效、灵活且可扩展的HTTP通信能力。它支持多种HTTP协议版本,包括HTTP/1.1和部分HTTP/2...
### Commons HTTPClient4.X 组件应用详解 #### 一、引言 ...传统的做法是使用浏览器或者基于JDK提供的`java.net`...对于需要频繁与Web服务器进行交互的应用程序而言,使用HttpClient4组件将极大提高开发效率和应用质量。
在这个“httpclient4 封装”中,我们将探讨HttpClient 4.2版本的使用,以及如何将它封装到自己的项目中。 HttpClient 4.2是Apache HttpClient系列的一个稳定版本,它支持HTTP/1.1和部分HTTP/2协议,提供了对HTTPS、...
本主题将深入探讨如何使用HttpClient4库进行百度和58同城的模拟登陆操作。HttpClient4是一个强大的Java库,它提供了丰富的功能来执行HTTP请求,非常适合进行网页交互。 首先,我们来了解HttpClient4的基本用法。...
4. **连接管理**:HttpClient提供了`PoolingHttpClientConnectionManager`,用于管理HTTP连接池,可以有效地复用连接,提高性能并减少网络资源消耗。 5. **Cookie管理**:HttpClient支持`CookieSpecs`和`...
本篇文章将详细介绍HTTPClient 4.0的使用方法,包括其核心概念、基本操作和示例代码。 一、核心概念 1. HttpClient实例:HttpClient对象是执行HTTP请求的核心,负责建立连接、发送请求和接收响应。通过`...