Java HttpClient4.2.x版本get、post请求工具类

公司业务需要,跟很多公司合作,经常需要请求外部http接口,而项目架构是一个比较老的框架整合,仅http请求的工具类就很多个,显得杂乱无章;

有些接口测试时,对方做了IP白名单限制的,ZIP压缩等要求,现有的http工具类无法满足要求,又不能去修改,因为很多地方在用;想引入最新HttpClient版本的依赖,确发现与现有的jar包冲突;

无耐只能使用现有的jar重新封装,具体代码演示如下:

post请求方式1

/**
* POST请求,超时时间必须设置
* @param url
* @param json JSON数据格式传参
* @return
*/
public static String post(String url, String json) {
String result = null;
HttpClient httpClient = null;
HttpPost httpPost = null;

try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(url);
// 连接超时设置
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
// 读取超时设置
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

StringEntity stringEntity = new StringEntity(json, Consts.UTF_8);
stringEntity.setContentEncoding(Consts.UTF_8.toString());
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);

HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
result = JSON.toJSONString(Result.error(e.getMessage()));
} finally {
// 终止本次请求
httpPost.abort();
// 释放连接
httpPost.releaseConnection();
httpClient.getConnectionManager().shutdown();
}

return result;
}

post请求方式2

/**
* POST请求,超时时间必须设置
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, String> params) {
String result = null;
HttpClient httpClient = null;
HttpPost httpPost = null;

try {
List<NameValuePair> pairs = new ArrayList<>();
for (Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(url);
// 连接超时设置
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
// 读取超时设置
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

StringEntity stringEntity = new UrlEncodedFormEntity(pairs, Consts.UTF_8);
httpPost.setEntity(stringEntity);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setHeader("Accept", "text/plain;charset=utf-8");
httpPost.setHeader("Accept-Encoding", "gzip, deflate");
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
result = JSON.toJSONString(Result.error(e.getMessage()));
} finally {
// 终止本次请求
httpPost.abort();
// 释放连接
httpPost.releaseConnection();
httpClient.getConnectionManager().shutdown();
}

return result;
}

get请求

/**
* GET请求,超时时间必须设置
* @param url
* @param params Map<String, String>数据格式传参
* @return
*/
public static String get(String url, Map<String, String> params) {
String result = null;
HttpClient httpClient = null;
HttpGet httpGet = null;

try {
List<NameValuePair> pairs = new ArrayList<>();
for (Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
URI uri = new URI(url + "?" + URLEncodedUtils.format(pairs, Consts.UTF_8));

httpClient = new DefaultHttpClient();
httpGet = new HttpGet(uri);

// 连接超时设置
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
// 读取超时设置
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
result = JSON.toJSONString(Result.error(e.getMessage()));
} finally {
httpGet.abort();
httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
}

return result;
}

post请求代理方式

/**
* GET请求,超时时间必须设置
* @param url
* @param params Map<String, String>数据格式传参
* @return
*/
public static String get(String url, Map<String, String> params) {
String result = null;
HttpClient httpClient = null;
HttpGet httpGet = null;

try {
List<NameValuePair> pairs = new ArrayList<>();
for (Entry<String, String> entry : params.entrySet()) {
pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
URI uri = new URI(url + "?" + URLEncodedUtils.format(pairs, Consts.UTF_8));

httpClient = new DefaultHttpClient();
httpGet = new HttpGet(uri);

// 连接超时设置
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 15000);
// 读取超时设置
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, Consts.UTF_8);
}
} catch (Exception e) {
e.printStackTrace();
result = JSON.toJSONString(Result.error(e.getMessage()));
} finally {
httpGet.abort();
httpGet.releaseConnection();
httpClient.getConnectionManager().shutdown();
}

return result;
}

原文地址:https://www.cnblogs.com/james-i71/p/9988173.html

时间: 2024-11-06 08:56:19

Java HttpClient4.2.x版本get、post请求工具类的相关文章

java jdk原生的http请求工具类

package com.base; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net

我的Android进阶之旅------&gt;Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEn

JavApi 以类似 Java API 的形式提供一组 .NET 的工具类

javApi 以类似 Java API 的形式提供一组 .NET 的工具类. 下面是一些示例代码: SampleGZIPOutputStream2File.cs: GZip a file content into other file.?(Example for: FileInputStream, FileOutputStream, GZIPOutputStream) SampleTextFileOutputStream.cs: Write text or binaries to file.?(

iOS_21团购_通过block对请求工具类的代理方法进行二次封装

最终效果图: [点评]提供的工具类DPAPI 在请求完毕后,使用的是代理机制,当一次请求成功或者失败时,会调用代理的相应方法 为了将点评提供的工具类DPAPI进行二次封装, 再次定义了一个block: typedef  void(^RequestDoneCallBackBlock)(id deals,NSError *err); 该block有两个参数, 分别是成功时,服务器返回的deals字典数组 另一个参数是:请求失败时,服务器返回的失败信息 两个参数分别对应代理的两个方法(即成功.失败时分

Java并发(十六):并发工具类——Exchanger

Exchanger(交换者)是一个用于线程间协作的工具类.Exchanger用于进行线程间的数据交换.它提供一个同步点,在这个同步点两个线程可以交换彼此的数据.这两个线程通过exchange方法交换数据, 如果第一个线程先执行exchange方法,它会一直等待第二个线程也执行exchange,当两个线程都到达同步点时,这两个线程就可以交换数据,将本线程生产出来的数据传递给对方. 举例 class ExchangerTest { static class Producer implements R

java 实体对象与Map之间的转换工具类(自己还没看)

java实体对象与Map之间的转换工具类 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class EntityUtils { /** * 实体类转Map * @param object * @return */ public static Map<String, Object> entityToMap(Object object) { Map<String,

Java http请求工具类

该工具类可以调用POST请求或者Get请求,参数以Map的方式传入,支持获获取返回值,返回值接收类型为String HttpRequestUtil.java package com.util; import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.List;import java.ut

HttpInvoker http请求工具类

1 import java.io.BufferedReader; 2 import java.io.DataOutputStream; 3 import java.io.IOException; 4 import java.io.InputStreamReader; 5 import java.net.HttpURLConnection; 6 import java.net.URL; 7 import java.util.Map; 8 9 /** 10 * HTTP请求类 11 * @autho

【JDBC编程】Java 连接 MySQL 基本过程以及封装数据库工具类

鉴于linux系统下安装oracle数据库过于麻烦,而相关的java连接mysql基本方法的参考文章过少且参差不齐,故本人查阅了一些书和网络资料写下此文章. 从数据库环境搭建.基本语法到封装工具类全过程,可作为参考.转载请注明来源. 一. 常用的JDBC API 1. DriverManager类 : 数据库管理类,用于管理一组JDBC驱动程序的基本服务.应用程序和数据库之间可以通过此类建立连接.常用的静态方法如下 static connection getConnection(String u