import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.StringEntity;
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.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.springframework.http.MediaType;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
* @author tracyclock
* 2017.12.25
* httpurlconnection 和 httpclient 发送get、post请求
*/
public class HttpRequestUtil {
private static String postParam = "{\"userId\":\"999\",\"pos\":\"12.3201562,30.2456244\",\"buildIp\":\"127.0.0.1\",\"buildDvcid\":\"iphone6s\",\"buildModel\":\"1\",\"token\":\"fdgr456u6783grh\",\"type\":\"EID_INFO\"}";
private static String getUrl = "http://127.0.0.1:8022/getTest";
private static String postUrl = "http://127.0.0.1:8022/qrcode/eid/buildEidQr";
/**
* 向指定URL发送GET方法的请求
*/
public static String sendGet(String url) {
String result = "";
BufferedReader bufferedReader = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
//设置通用的请求属性,也可不做设置
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//建立实际的连接
connection.connect();
//定义 BufferedReader输入流来读取URL的响应
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*/
public static String sendPost(String url, String param,String paramFormat) {
StringBuffer result = new StringBuffer();
InputStream in = null;
PrintWriter out = null;
BufferedReader bufferedReader = null;
try {
URL realUrl = new URL(url);
//打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
//设置通用的请求属性,也可不做设置
connection.setRequestProperty("content-type", paramFormat);//指定参数格式
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//发送POST请求必须设置如下两行,因为doOutput的默认值是false
connection.setDoOutput(true);
connection.setDoInput(true);
//获取HttpURLConnection对象对应的输出流
out = new PrintWriter(connection.getOutputStream());
out.print(param);
out.flush();
//建立连接
connection.connect();
//获取URL的响应
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
in = connection.getInputStream();
} else {
in = connection.getErrorStream();
}
//result接收BufferedReader读取URL的响应
bufferedReader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(bufferedReader != null){
bufferedReader.close();
}
if(out != null){
out.close();
}
if(in != null){
in.close();
}
}catch (IOException e) {
e.printStackTrace();
}
}
return result.toString();
}
/**
* 将map形式的参数拼接get请求的参数字符串。
*/
public static String buildGetParam(Map<String, Object> dataMap) {
StringBuilder formStr = new StringBuilder();
for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
if (entry.getValue() != null) {
formStr.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
}
}
int length = formStr.length();
if (length != 0) {
formStr.deleteCharAt(length - 1);
}
return formStr.toString();
}
/**
* 将object转化为json格式的字符串
*/
public static String getJsonStr(Object object){
if(object == null){
return null;
}
ObjectMapper json = new ObjectMapper();
String jsonStr = "";
try {
jsonStr = json.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return jsonStr;
}
/**
* 发送 HttpGet 请求
*/
public static String httpDoGet(String url){
String result = "";
CloseableHttpResponse response;
HttpGet httpGet = new HttpGet(url);
try {
response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
result = getResponseStr(response);
} catch (IOException e) {
e.printStackTrace();
}finally {
httpGet.abort();
}
return result;
}
/**
* 发送 HttpPost 请求
*/
public static String httpDoPost(String url, String param) {
String result = "";
CloseableHttpResponse response;
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
try {
StringEntity se = new StringEntity(param);
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE));
httpPost.setEntity(se);
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("HttpClient HttpPost() error status code :" + statusCode);
}
result = getResponseStr(response);
} catch (Exception e) {
e.printStackTrace();
} finally {
httpPost.abort();
}
return result;
}
/**
* 将response返回的实体信息转化成字符串
*/
public static String getResponseStr(HttpResponse response){
if (response != null) {
BufferedReader br = null;
try {
if (response.getEntity() == null) {
return null;
}
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
StringBuffer sb = new StringBuffer();
String result;
while ((result = br.readLine()) != null) {
sb.append(result);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
/**
* 创建CloseableHttpClient 线程池
* 用CloseableHttpClient,可以保证httpClient.execute()执行的response最终被close掉
*/
private static CloseableHttpClient httpClient;
static{
//当出现连接超时或应答超时的情况,如果没有超时处理,会导致内存不足、或线程池被用光,需要设置timeout
RequestConfig requestConfig = RequestConfig.custom()
//从连接池获取连接
.setConnectionRequestTimeout(30000)
//连接超时
.setConnectTimeout(15000)
//服务响应超时
.setSocketTimeout(30000)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
//单路由最大连接
cm.setDefaultMaxPerRoute(100);
cm.setMaxTotal(100);
//设置默认请求头
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, Locale.CHINA.toString()));
httpClient = HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(cm)
.setDefaultHeaders(headers)
.setKeepAliveStrategy((httpResponse, httpContext) -> 10 * 1000)
.build();
}
public static void main(String[] args) {
//get测试需要的参数
Map<String,Object> map = new HashMap<>();
map.put("name","ha");
String url = getUrl + "?" + buildGetParam(map);
//httpUrlConnection get测试
String httpUrlConnectionGetResult = sendGet(url);
System.out.println("httpUrlConnection get Result ----------"+httpUrlConnectionGetResult);
//httpUrlConnection post测试
String httpUrlConnectionPostResult = sendPost(postUrl,postParam, MediaType.APPLICATION_JSON_VALUE);
System.out.println("httpUrlConnection post Result -------------" + httpUrlConnectionPostResult);
//httpClient get测试
String httpClientGetResult = httpDoGet(url);
System.out.println("httpClient get Result ----------"+ httpClientGetResult);
//httpClient post测试
String httpClientPostResult = httpDoPost(postUrl,postParam);
System.out.println("httpClient post Result ----------"+ httpClientPostResult);
}
}
打印结果:
httpUrlConnection get Result ----------this is tracyClock
httpUrlConnection post Result -------------{"success":true,"resultCode":0,"data":"{\"A\":1,\"K\":\"/ndUowQir7xjPtVAM8/akOKzSMT8q24NrgSHcCzfgY0=\",\"P\":\"12.3201562,30.2456244\",\"S\":\"MEUCIQDbWsGnsXDvORfZ14D5E+maKXvS/fEluKV0/hq6XR8o6QIgbMOZrNxOd7xTGlFHrcsFWriS\\r\\noJpWAyWIagyhz9duv4Q=\\r\\n\",\"T\":1514169504505,\"V\":\"1\"}"}
httpClient get Result ----------this is tracyClock
httpClient post Result ----------{"success":true,"resultCode":0,"data":"{\"A\":1,\"K\":\"/ndUowQir7xjPtVAM8/akB/iWu0GD6L4PJP2XG1YppM=\",\"P\":\"12.3201562,30.2456244\",\"S\":\"MEUCIQDLe2O1FPfFW9/WRNMNFxucn9orMEgOVZiRjICf54dFlgIgE0MR3doPUM1qY32K1lcPwLHP\\r\\nJzSJ1edT+UkghcnNs08=\\r\\n\",\"T\":1514169504607,\"V\":\"1\"}"}