java-httpclient
1.maven
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.41</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.8</version>
</dependency>
2.实例
2.1 GET
public static String doGet(String url, Map<String, String> params) {
String result = "";
RequestConfig reqConfig = RequestConfig.custom()
.setSocketTimeout(60 * 1000)
.setConnectTimeout(10 * 1000)
.setConnectionRequestTimeout(10 * 1000)
.build();
HttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(reqConfig)
.build();
HttpGet httpGet = null;
try {
URIBuilder uriBuilder = new URIBuilder(url);
if (null != params && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
}
}
URI uri = uriBuilder.build();
httpGet = new HttpGet(uri);
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity());
log.info("doGetSuccess({}):{}",url, result);
} else {
log.error("doGetFail({}):{}", url, response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
log.error("doGetError({}):{}", url, ExceptionUtils.getStackTrace(e));
} finally {
if (null != httpGet) {
httpGet.releaseConnection();
}
}
return result;
}
2.2 POST-Common
public static String doPost(String url, Map<String, String> params) {
String result = "";
RequestConfig reqConfig = RequestConfig.custom()
.setSocketTimeout(60 * 1000)
.setConnectTimeout(10 * 1000)
.setConnectionRequestTimeout(10 * 1000)
.build();
HttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(reqConfig)
.build();
HttpPost httpPost = new HttpPost(url);
try {
if (null != params && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
NameValuePair pair = null;
for (String key : params.keySet()) {
pair = new BasicNameValuePair(key, params.get(key));
pairs.add(pair);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs);
httpPost.setEntity(entity);
}
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(response.getEntity(), "utf-8");
log.info("doPostSuccess({}):{}",url, result);
} else {
log.error("doPostFail({}):{}", url, response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
log.error("doPostError({}):{}", url,ExceptionUtils.getStackTrace(e));
e.printStackTrace();
} finally {
if (null != httpPost) {
httpPost.releaseConnection();
}
}
return result;
}
2.3 POST-Json
public static String sendJson (String url, JSONObject jsonObject) {
String result = "";
RequestConfig reqConfig = RequestConfig.custom()
.setSocketTimeout(60 * 1000)
.setConnectTimeout(10 * 1000)
.setConnectionRequestTimeout(10 * 1000)
.build();
HttpClient httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(reqConfig)
.build();
HttpPost httpPost = new HttpPost(url);
try {
httpPost.addHeader("Content-type", "application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
if (StringUtils.isNotBlank(jsonObject.toString())) {
httpPost.setEntity(new StringEntity(jsonObject.toString(), StandardCharsets.UTF_8));
}
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
if (entity != null){
result = JSONObject.parseObject(EntityUtils.toString(entity, StandardCharsets.UTF_8)).toJSONString();
}
}else {
log.error("sendJsonFail({}):{}",url, response.getStatusLine().getStatusCode());
}
} catch (Exception e) {
log.error("sendJsonError({}):{}",url, ExceptionUtils.getStackTrace(e));
}finally {
if (null != httpPost) {
httpPost.releaseConnection();
}
}
return result;
}
2.4 POST-File
public static String sendFilePost(String url, Map<String, ContentBody> reqParam){
CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
HttpPost httppost = new HttpPost(url);
RequestConfig reqConfig = RequestConfig.custom()
.setSocketTimeout(60 * 1000)
.setConnectTimeout(10 * 1000)
.setConnectionRequestTimeout(10 * 1000)
.build();
httppost.setConfig(reqConfig);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntityBuilder.setCharset(StandardCharsets.UTF_8);
for(Map.Entry<String,ContentBody> param : reqParam.entrySet()){
multipartEntityBuilder.addPart(param.getKey(), param.getValue());
}
HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
return JSONObject.parseObject(EntityUtils.toString(entity, StandardCharsets.UTF_8)).toJSONString();
}
} catch (IOException e){
e.printStackTrace();
log.error("请求-{}-响应异常:{}", url, String.valueOf(e));
}
} finally {
try {
if (response != null){
response.close();
}
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
log.error("请求-{}-内部异常:{}", url, String.valueOf(e));
}
}
return null;
}


【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探