package com.reptile.util.http; import java.io.IOException; import java.nio.charset.UnsupportedCharsetException; import org.apache.http.HttpEntity; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpUtils { public static String httpClientPost(String url,String jsonData) { String result; try { result = ""; CloseableHttpClient client = HttpClients.createDefault(); HttpPost httpPost=new HttpPost(url); StringEntity stringEntity=new StringEntity(jsonData, ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); httpPost.addHeader("content-type", "application/json;chartset=UTF-8"); RequestConfig config = RequestConfig.custom() // 连接请求超时ms .setConnectTimeout(1000) // 连接超时时间ms .setConnectionRequestTimeout(1000) // 读取超时ms .setSocketTimeout(10 * 1000).build(); httpPost.setConfig(config); CloseableHttpResponse execute = client.execute(httpPost); HttpEntity entity = execute.getEntity(); String content = EntityUtils.toString(entity, "utf-8"); result = content; return result; } catch (UnsupportedCharsetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
调用
pom.xml
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.10</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.6</version> </dependency>
pom引入或jar引入,不论引入多少版本的,只要不报错,基本都可以使用
还没有评论,来说两句吧...