package cn.cq.shenyun; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.http.*; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.*; import org.apache.http.config.ConnectionConfig; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.LayeredConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; public class HttpUtilDemo { private static final Logger logger = LoggerFactory.getLogger(HttpUtilDemo.class); private static int SocketTimeout = 3000;//3秒 private static int ConnectTimeout = 3000;//3秒 private static Boolean SetTimeOut = true; private static CloseableHttpClient getHttpClient() { RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create(); ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory(); registryBuilder.register("http", plainSF); //指定信任密钥存储对象和连接套接字工厂 try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); //信任任何链接 TrustStrategy anyTrustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build(); LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); registryBuilder.register("https", sslSF); } catch (KeyStoreException e) { throw new RuntimeException(e); } catch (KeyManagementException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } Registry<ConnectionSocketFactory> registry = registryBuilder.build(); //设置连接管理器 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry); // connManager.setDefaultConnectionConfig(connConfig); // connManager.setDefaultSocketConfig(socketConfig); //构建客户端 return HttpClientBuilder.create().setConnectionManager(connManager).build(); } /** * get * * @param url 请求的url * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null * @return * @throws IOException */ public static String get(String url, Map<String, String> queries) throws IOException { String responseBody = ""; //CloseableHttpClient httpClient=HttpClients.createDefault(); //支持https CloseableHttpClient httpClient = getHttpClient(); StringBuilder sb = new StringBuilder(url); if (queries != null && queries.keySet().size() > 0) { boolean firstFlag = true; Iterator iterator = queries.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry<String, String>) iterator.next(); if (firstFlag) { sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue()); firstFlag = false; } else { sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue()); } } } HttpGet httpGet = new HttpGet(sb.toString()); if (SetTimeOut) { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SocketTimeout) .setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间 httpGet.setConfig(requestConfig); } try { System.out.println("Executing request " + httpGet.getRequestLine()); //请求数据 CloseableHttpResponse response = httpClient.execute(httpGet); System.out.println(response.getStatusLine()); int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); // do something useful with the response body // and ensure it is fully consumed responseBody = EntityUtils.toString(entity); //EntityUtils.consume(entity); } else { System.out.println("http return status error:" + status); throw new ClientProtocolException("Unexpected response status: " + status); } } catch (Exception ex) { ex.printStackTrace(); } finally { httpClient.close(); } return responseBody; } /** post * @param url 请求的url * @param queries 请求的参数,在浏览器?后面的数据,没有可以传null * @param params post form 提交的参数 * @return * @throws IOException */ public static String post(String url, Map<String, String> queries, Map<String, String> params) throws IOException { String responseBody = ""; //CloseableHttpClient httpClient = HttpClients.createDefault(); //支持https CloseableHttpClient httpClient = getHttpClient(); StringBuilder sb = new StringBuilder(url); if (queries != null && queries.keySet().size() > 0) { boolean firstFlag = true; Iterator iterator = queries.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry<String, String>) iterator.next(); if (firstFlag) { sb.append("?" + (String) entry.getKey() + "=" + (String) entry.getValue()); firstFlag = false; } else { sb.append("&" + (String) entry.getKey() + "=" + (String) entry.getValue()); } } } //指定url,和http方式 HttpPost httpPost = new HttpPost(sb.toString()); if (SetTimeOut) { RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(SocketTimeout) .setConnectTimeout(ConnectTimeout).build();//设置请求和传输超时时间 httpPost.setConfig(requestConfig); } //添加参数 List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (params != null && params.keySet().size() > 0) { Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next(); nvps.add(new BasicNameValuePair((String) entry.getKey(), (String) entry.getValue())); } } httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); //请求数据 CloseableHttpResponse response = httpClient.execute(httpPost); try { System.out.println(response.getStatusLine()); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); // do something useful with the response body // and ensure it is fully consumed responseBody = EntityUtils.toString(entity); //EntityUtils.consume(entity); } else { System.out.println("http return status error:" + response.getStatusLine().getStatusCode()); } } catch (Exception e) { e.printStackTrace(); } finally { response.close(); } return responseBody; } public static void main(String[] args) throws Exception{ System.out.println(get("url", null)); } }
http://blog.csdn.net/shenyunsese/article/details/41075579
相关推荐
2. HTTPS支持:HttpClient可以配置SSLContext,支持HTTPS连接,同时可以处理自签名证书和特定的TrustManager。 3. 缓存机制:HttpClient支持HTTP缓存规范,可以减少网络I/O,提高性能。 4. 高级特性:如自动处理...
这个"HttpClient for android 4.3.5 jar"包含了两个文件:`httpclient-android-4.3.5-sources.jar`和`httpclient-android-4.3.5.jar`。 `httpclient-android-4.3.5-sources.jar`是源码版本的jar文件,它包含了...
`httpclient-4.3.1`是该库的一个特定版本,它包含了对HTTP协议的支持,包括支持HTTP/1.1和部分HTTP/2特性。这个版本可能已经过时,因为最新版本是HTTPClient 4.5.x或更高版本,但理解旧版本的使用仍然是有价值的,...
例如,你可以使用HttpClient来发起HTTP请求,通过HTTP Core库进行网络通信,而HTTP Mime则帮助处理含有MIME类型的请求和响应数据。为了更好地利用这些库,开发者需要了解HTTP协议的基本概念,如方法(GET、POST等)...
HttpClient支持各种HTTP协议特性,如HTTP/1.0和HTTP/1.1,以及HTTPS、连接管理、重定向处理、cookies管理等。它还支持异步请求处理,使得在高并发环境下更有效率。 **Apache HttpCore 4.3.2** HttpCore是HttpClient...
4. **Entity Encoders/Decoders**: 提供对HTTP实体(请求或响应体)的编码和解码,支持各种数据格式,如文本、二进制、流等。 接下来是HTTPMIME,它是处理HTTP消息内容的组件,特别是在处理MIME类型的请求和响应时...
`httpclient-4.3.5.jar`是Apache HttpClient库的一个版本,它提供了一种强大的HTTP客户端实现,用于执行HTTP请求并处理响应。虽然主要设计为Web服务交互,但HttpClient也常被用来支持FTP,因为它可以处理FTP通过...
- 特性包括支持HTTP/1.1、HTTPS、连接池管理、请求路由、重试策略、多种认证机制等。 - 使用HttpAsyncClient,开发者可以通过回调函数或者Future对象来处理异步响应,增强了灵活性。 2. **HttpCore 4.3.2**: - ...
3. **httpmime-4.3.5.jar**:这个库是HttpClient的一个扩展,主要用于处理HTTP请求中的MIME类型数据。在与图灵机器人交互时,如果需要发送复杂的数据结构,比如JSON格式的请求体,httpmime库就可以帮助构建和序列化...
首先,`httpclient-4.3.5.jar`是Apache HttpClient的核心库,它提供了丰富的API用于发送HTTP请求和接收响应。HttpClient支持各种HTTP方法(如GET、POST),可以处理cookies以保持会话状态,同时还能处理重定向、HTTP...
在文件上传时,我们通常会用到`HttpClient`对象来发起POST请求,以及`HttpPost`类来构建具体的POST请求实例。通过`setEntity`方法,我们可以将`httpmime`库构造的MIME实体设置到HTTP POST请求中。 以下是使用这两个...
- 通过引入HttpClient依赖,可以在Java代码中模拟HTTP请求,获取响应数据。 - 常见应用场景包括数据抓取(爬虫)、API调用等。 - **示例代码**: - Maven依赖配置: ```xml <groupId>org.apache....
1. **httpclient-4.3.5.jar**: 这是Apache HttpClient库的一个版本,用于HTTP客户端通信。它提供了丰富的API来执行HTTP请求,处理响应,并支持连接池管理、重试策略等功能。在微信支付的场景中,它可能用于与微信...
1. **httpclient-4.3.5.jar**:这是Apache HttpClient库的版本4.3.5,它提供了在Java应用程序中执行HTTP请求的功能。HttpClient支持HTTP/1.1协议,包括GET、POST等方法,是Elasticsearch进行网络通信的重要组件。 2...
1. httpclient-4.3.5.jar:这是Apache HttpClient库的一个版本,它提供了HTTP协议的客户端实现。开发者可以使用这个库来发送HTTP请求,接收响应,进行网络通信。HttpClient支持多种HTTP方法(如GET、POST)、连接...
- **6.4 数据存储之Network**: 通过网络请求从服务器获取或上传数据。 - **6.5 Android数据库编程** - **6.5.1 SQLite简介**: SQLite是一款轻量级的关系型数据库管理系统,非常适合移动设备。 - **6.5.2 SQLite...