HttpRequestUtil工具类
import io.micrometer.core.instrument.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class HttpRequestUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpRequestUtil.class);
public static String sendGet(String url) throws IOException {
return sendGet(url, null);
}
public static String sendGet(String url, String param) throws IOException {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
if (StringUtils.isNotBlank(param)) {
urlNameString += "?" + param;
}
URL realUrl = new URL(urlNameString);
URLConnection connection = 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();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, String param, String token) throws IOException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
if (token != null && !"".equals(token)) {
conn.setRequestProperty("token", token);
}
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("发送 POST 请求出现异常!", e);
throw e;
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String sendPost(String url, String param) throws IOException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("发送 POST 请求出现异常!", e);
throw e;
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String sendPost(String url) throws IOException {
return sendPost(url, "");
}
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
StringBuffer buffer = null;
try {
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
if (null != outputStr) {
OutputStream os = conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
InputStream is = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
buffer = new StringBuffer();
String line = null;
while ((line = br.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer.toString();
}
}
详细版
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
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.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpUtil {
private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
public static String get(String url, Map<String, String> headerMap) throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
if (null != headerMap) {
headerHandle(headerMap, false);
headerMap.forEach(request::addHeader);
}
HttpResponse response = client.execute(request);
String responseBody = responseHandle(response);
request.releaseConnection();
return responseBody;
}
public static String delete(String url, Map<String, String> headerMap) throws IOException {
HttpClient client = HttpClientBuilder.create().build();
HttpDelete request = new HttpDelete(url);
if (null != headerMap) {
headerHandle(headerMap, false);
headerMap.forEach(request::addHeader);
}
HttpResponse response = client.execute(request);
String responseBody = responseHandle(response);
request.releaseConnection();
return responseBody;
}
public static String put(String url, Map<String, String> headerMap, Object requestBody) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPut request = new HttpPut(url);
headerHandle(headerMap, true);
headerMap.forEach(request::addHeader);
request.setEntity(requestBodyHandle(requestBody));
HttpResponse response = httpClient.execute(request);
String responseBody = responseHandle(response);
request.releaseConnection();
return responseBody;
}
public static String post(String url, Object requestBody) throws IOException {
return post(url,new HashMap<>(),requestBody);
}
public static String post(String url, Map<String, String> headerMap, Object requestBody) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
headerHandle(headerMap, true);
headerMap.forEach(request::addHeader);
request.setEntity(requestBodyHandle(requestBody));
logger.info("请求参数: {}", JSONObject.toJSONString(requestBody));
logger.info("请求头:{}", request.getAllHeaders());
logger.info("requestUrl :{}", url);
HttpResponse response = httpClient.execute(request);
logger.info("HttpResponse : {}", JSONObject.toJSONString(response));
String responseBody = responseHandle(response);
request.releaseConnection();
return responseBody;
}
public static String patch(String url, Map<String, String> headerMap, Object requestBody) throws IOException {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPatch request = new HttpPatch(url);
headerHandle(headerMap, true);
headerMap.forEach(request::addHeader);
request.setEntity(requestBodyHandle(requestBody));
HttpResponse response = httpClient.execute(request);
String responseBody = responseHandle(response);
request.releaseConnection();
return responseBody;
}
public static String get(String url) throws IOException{
return get(url, null);
}
private static void headerHandle(Map<String, String> headerMap, boolean contentType) {
if (null == headerMap) {
headerMap = new HashMap<>();
}
if (contentType) {
headerMap.put("Content-type", "application/json");
}
}
private static StringEntity requestBodyHandle(Object requestBody) {
String paramsStr = JsonUtil.toJsonString(requestBody);
return requestBody == null ? null : new StringEntity(paramsStr, "UTF-8");
}
public static String responseHandle(HttpResponse response) throws IOException {
ResponseHandler<String> handler = new BasicResponseHandler();
StatusLine statusLine = response.getStatusLine();
int responseCode = statusLine.getStatusCode();
String responseBody;
if (responseCode == 200) {
responseBody = handler.handleResponse(response);
} else if (responseCode == 403) {
responseBody = handler.handleResponse(response);
} else if (responseCode == 204) {
responseBody = null;
} else {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
return responseBody;
}
public static String readAsChars(HttpServletRequest request) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder("");
try {
br = request.getReader();
String str;
while ((str = br.readLine()) != null)
{
sb.append(str);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static String doPost (String url, Map<String, String> urlParam, Map<String, String> headerMap, String body) {
CloseableHttpResponse response = null;
try {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(6000)
.setConnectTimeout(6000)
.setConnectionRequestTimeout(6000)
.build();
CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
StringBuilder param=new StringBuilder("");
if (null != urlParam){
for (String key:urlParam.keySet()){
param.append(key + "=" + URLEncoder.encode(urlParam.get(key), "UTF-8") + "&");
}
}
HttpPost httpPost = new HttpPost(url+param.toString());
if(StringUtil.isNotEmpty(body)){
StringEntity entity=new StringEntity(body, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
}
if (null != headerMap){
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, "UTF-8");
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage(), e);
} catch (ClientProtocolException e) {
logger.error(e.getMessage(), e);
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (Exception e){
System.out.println(e);
}finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
return null;
}
}