HttpClient 4.3
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientUtil {
//post
public static String PostApi(String apiUrl,String requestBody,String contentType,String encode)
throws Exception {
// 创建默认的httpClient实例
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httpPost = new HttpPost(apiUrl);
//requestBody
StringEntity entity = new StringEntity(requestBody, ContentType.create(contentType,encode));
httpPost.setEntity(entity);
// 设置请求和响应超时
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpPost.setConfig(requestConfig);
String responseMsg="";
try {
CloseableHttpResponse response = httpclient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
//响应的数据
responseMsg=EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
responseMsg="{E:\"请求失败\"}";
} finally {
httpclient.close();
}
return responseMsg;
}
//get
public static String GetApi(String apiUrl) throws Exception{
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httpget
HttpGet httpGet = new HttpGet(apiUrl);
//设置请求和响应超时
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000).build();
httpGet.setConfig(requestConfig);
String responseMsg="";
try {
//发送请求并返回响应数据
CloseableHttpResponse response = httpclient.execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
//响应的数据
responseMsg=EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
responseMsg="{E:\"请求失败\"}";
} finally{
httpclient.close();
}
return responseMsg;
}
}