另外一个版本: http://www.cnblogs.com/wenbronk/p/6671928.html

在java代码中调用http请求, 并将返回的参数进行处理

get请求:

    public static String doGet(String getUrl) throws IOException {
String str = null;
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
// HttpClient httpclient = new DefaultHttpClient();
// HttpGet("http://www.wenbronk.com/geosot-basis/getGeoNum?lng=21.12&lat=1&geoLevel=17");
HttpGet httpgets = new HttpGet(getUrl);
HttpResponse response = httpclient.execute(httpgets);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
str = convertStreamToString(instreams);
httpgets.abort();
}
}catch (Exception e) { }
return str;
}

最开始使用了过时的类DefaultHttpClient, 结果引发一大堆问题, 后台改成了CloseableHttpClient

post请求: 传入参数为字符串, 这里为业务需求所以传入的为json格式的字符串

    private static String doPost(String postUrl, JSONObject jsonObj) throws ClientProtocolException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
// HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(postUrl);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String str = null;
StringEntity s = new StringEntity(jsonObj.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(s);
CloseableHttpResponse response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
str = convertStreamToString(instreams);
post.abort();
}
System.out.println(str);
return str;
}

响应信息处理类:

    private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

2017/3/1: 后因频繁调用次数过多, 加入HttpClient连接池

package com.iwhere.util;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException; import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException; import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext; public class HttpClientPool { public static CloseableHttpClient getHttpClient() {
ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainsf)
.register("https", sslsf)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
// 将最大连接数增加到200
cm.setMaxTotal();
// 将每个路由基础的连接增加到20
cm.setDefaultMaxPerRoute();
// 将目标主机的最大连接数增加到50
// HttpHost localhost = new HttpHost("http://dev.iwhere.com",8010);
// cm.setMaxPerRoute(new HttpRoute(localhost), 70); //请求重试处理
HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception,int executionCount, HttpContext context) {
if (executionCount >= ) {// 如果已经重试了5次,就放弃
return false;
}
if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
return true;
}
if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
return false;
}
if (exception instanceof InterruptedIOException) {// 超时
return false;
}
if (exception instanceof UnknownHostException) {// 目标服务器不可达
return false;
}
if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
return false;
}
if (exception instanceof SSLException) {// ssl握手异常
return false;
} HttpClientContext clientContext = HttpClientContext.adapt(context);
HttpRequest request = clientContext.getRequest();
// 如果请求是幂等的,就再次尝试
if (!(request instanceof HttpEntityEnclosingRequest)) {
return true;
}
return false;
}
}; return HttpClients.custom().setConnectionManager(cm).setRetryHandler(httpRequestRetryHandler).build();
} }

使用httpClient处理get请求或post请求的更多相关文章

  1. HttpClient发送Post请求,get请求

    // 创建默认的httpclient实例 CloseableHttpClient httpclient = getHttpClient(); CloseableHttpResponse respons ...

  2. httpClient 中的post或者get请求

    httpClient相对于java自带的请求功能更加强大,下面就以例子的形式给出: //HttpClient Get请求 private static void register() { try { ...

  3. JAVA发送HttpClient请求及接收请求结果

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...

  4. httpclient实现的get请求及post请求

    导出mven依赖 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId& ...

  5. JAVA发送HttpClient请求及接收请求结果过程

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 ...

  6. 封装HttpClient进行http请求与https请求

    一.https忽略证书 /** * 用于进行Https请求的HttpClient * * @author joey * */ public class SSLClient { public stati ...

  7. HttpClient之用CloseableHttpClient发送post请求

    使用HttpClient发送请求的一般步骤(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创 ...

  8. HttpClient之Get请求和Post请求示例

    HttpClient之Get请求和Post请求示例 博客分类: Java综合   HttpClient的支持在HTTP/1.1规范中定义的所有的HTTP方法:GET, HEAD, POST, PUT, ...

  9. WebApi系列~基于单请求封装多请求的设计

    回到目录 怎么说,单请求封装多请求,这句话确实有点绕了,但还是要看清楚,想明白这到底是怎么一回事,单请求即一次请求(get,post,put,delete),封闭多请求,即在客户端发送的一个请求中可能 ...

  10. webapi基于单请求封装多请求的设计【转】

    怎么说,单请求封装多请求,这句话确实有点绕了,但还是要看清楚,想明白这到底是怎么一回事,单请求即一次请求(get,post,put,delete),封闭多请求,即在客户端发送的一个请求中可能包含多个子 ...

随机推荐

  1. java代码中存在的Big Endian 和 Little Endian

    Big Endian 和 Little Endian 详解 Java中的Big(Little)-endian问题的一种解决方法 主机序和网络序  很重要很重要 几种ip存放形式 Big-Endian和 ...

  2. Windows Server 2008 R2远程桌面服务配置和授权激活

    远程桌面服务安装好之后使用的是120天临时授权,所以会跳出以下提示,我们介绍远程桌面授权的激活. 现在我们使用命令 mstsc /admin 强制登录服务器 需要在“远程桌面服务”--安装“远程桌面授 ...

  3. 通过Spring Session实现新一代的Session管理

    长期以来,session管理就是企业级Java中的一部分,以致于我们潜意识就认为它是已经解决的问题,在最近的记忆中,我们没有看到这个领域有很大的革新. 但是,现代的趋势是微服务以及可水平扩展的原生云应 ...

  4. GeoServer中配置GeoWebCache切片缓存目录

    war版的GeoServer中,默认情况下,GeoWebCache切片会缓存在C盘某目录下.该目录比较隐蔽,并且随着切片缓存的增多,所占空间也会越来越大,所以建议手动配置其切换缓存目录. 配置方式:在 ...

  5. C#——调用C++的DLL 数据类型转换

    /C++中的DLL函数原型为        //extern "C" __declspec(dllexport) bool 方法名一(const char* 变量名1, unsig ...

  6. NetCore入门篇:(二)Net Core项目创建

    一.新建项目 1.选择菜单:文件 -> 新建 -> 项目 2.选择模板:NET Core -> ASP.NET Core Web 应用程序,输入名称 3.选择框架:ASP.NET C ...

  7. OI动态规划&&优化 简单学习笔记

    持续更新!! DP的难点主要分为两类,一类以状态设计为难点,一类以转移的优化为难点. DP的类型 序列DP [例题]BZOJ2298 problem a 数位DP 常用来统计或者查找一个区间满足条件的 ...

  8. HTTP/1.0中,状态码200 301 304 403 404 500的含义?

    200 OK 服务器成功处理了请求 301 重定向,请求的URL已移走 304未修改,客户的缓存资源是最新的,要客户端使用缓存 403禁止,请求被服务器拒绝了 404未找到资源 500内部服务器错误, ...

  9. include与file_get_contents区别

    参考:http://www.cnblogs.com/bgwan/archive/2013/03/13/2957215.html 一,先来说file_get_contents         这个函数就 ...

  10. tomcat安装配置常见问题详解

    历经波折,终于把tomcat装好了.记录下过程供自己和后来的初学者参考吧! 本文先后介绍了tomcat的下载安装方法.安装和启动不成功的常见原因 以及启动tomcat后如何配置上下文. 一.下载安装 ...