提前引入http相关依赖
org.apache.httpcomponents
httpcore
4.4.6
org.apache.httpcomponents
httpclient
4.5.2
org.apache.httpcomponents
httpmime
4.5.2
HTTP请求示例代码如下:
package com.itigation.tools;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;
/**
* Http请求工具类
*
* @author DaiHaijiao
*
*/
@SuppressWarnings("deprecation")
public class HttpUtil {
/**
* HTTP GET请求
*
* 此get请求若无参数,则params传null
*
* @param url
* 请求url路径
* @param params
* 参数map
* @param headerMap
* http请求的header组成的map
*
* @return 请求结果json字符串
* @throws ParseException
* @throws UnsupportedEncodingException
* @throws IOException
*/
public static String get(String url, Map params, Map headerMap) throws ParseException, UnsupportedEncodingException, IOException {
String jsonStr = null;
HttpGet httpGet = new HttpGet(getOrPutNewUrl(url, params));
if (null != headerMap && !headerMap.isEmpty()) {
for (String key : headerMap.keySet()) {
httpGet.setHeader(key, headerMap.get(key));
}
}
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(8000).build();
// CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
} else {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
throw new IllegalArgumentException(jsonStr);
}
return jsonStr;
}
/**
* HTTP PUT请求
*
* 此put请求若无参数,则params传null
*
* @param url
* 请求url路径
* @param params
* 参数map
* @return 请求结果json字符串
* @throws ClientProtocolException
* @throws IOException
*/
public static String put(String url, Map params) throws ClientProtocolException, IOException {
String jsonStr = null;
HttpPut httpPut = new HttpPut(getOrPutNewUrl(url, params));
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(8000).build();
// CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(httpPut);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
} else {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
throw new IllegalArgumentException(jsonStr);
}
return jsonStr;
}
/**
* 封装get请求参数
*
* @param url
* 请求url路径
* @param params
* 参数map
* @return 完整的get请求url
* @throws ParseException
* @throws UnsupportedEncodingException
* @throws IOException
*/
private static String getOrPutNewUrl(String url, Map params) throws ParseException, UnsupportedEncodingException, IOException {
if (null != params && !params.isEmpty()) {
List pairs = new ArrayList(params.size());
for (String key : params.keySet()) {
pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, "UTF-8"));
}
return url;
}
/**
* HTTP POST请求
*
* 此post请求若无参数,则params传null
*
* @param url
* 请求url路径
* @param params
* 参数map
* @param headerMap
* http请求的header组成的map
* @return 请求结果json字符串
* @throws ClientProtocolException
* @throws IOException
*/
public static String httpPost(String url, Map params, Map headerMap) throws ClientProtocolException, IOException {
String jsonStr = null;
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(8000).build();
// CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
if (null != headerMap && !headerMap.isEmpty()) {
for (String key : headerMap.keySet()) {
httpPost.setHeader(key, headerMap.get(key));
}
}
if (null != params && !params.isEmpty()) {
setPostParams(params, httpPost);
}
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
} else {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
throw new IllegalArgumentException(jsonStr);
}
return jsonStr;
}
/**
* HTTP POST请求参数封装
*
* @param params
* 参数map
* @param httpPost
* HttpPost对象
* @throws UnsupportedEncodingException
*/
private static void setPostParams(Map params, HttpPost httpPost) throws UnsupportedEncodingException {
if (null != params) {
List formParams = new ArrayList();
for (Map.Entry entry : params.entrySet()) {
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
}
httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
}
}
/**
* HTTP POST请求
*
* @see此post请求若无参数,则params传null;若无文件,则file和fileKey都传null
*
* @param url
* 请求url
* @param params
* 请求参数
* @param file
* 请求文件
* @param fileKey
* 文件对应key,接口通过此key接收文件
* @param headerMap
* http请求的header
* @return 请求结果json字符串
* @throws ClientProtocolException
* @throws IOException
*/
public static String post(String url, Map params, File file, String fileKey, Map headerMap) throws ClientProtocolException, IOException {
String jsonStr = null;
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(8000).build();
// CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
if (null != headerMap && !headerMap.isEmpty()) {
for (String key : headerMap.keySet()) {
httpPost.setHeader(key, headerMap.get(key));
}
}
httpPost.setEntity(postParamsEntry(params, file, fileKey));
CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
} else {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
throw new IllegalArgumentException(jsonStr);
}
return jsonStr;
}
/**
* 封装post请求参数
*
* @param params
* 参数map
* @param file
* 文件对象
* @param fileKey
* 文件对应的key
* @return MultipartEntity对象
* @throws UnsupportedEncodingException
*/
private static MultipartEntity postParamsEntry(Map params, File file, String fileKey) throws UnsupportedEncodingException {
MultipartEntity entity = new MultipartEntity();
if (null != file && file.isFile() && null != fileKey && !"".equals(fileKey.trim())) {
FileBody fileBody = new FileBody(file);
FormBodyPart filePart = new FormBodyPart(fileKey, fileBody);
entity.addPart(filePart);
}
if (null != params && !params.isEmpty()) {
Iterator iterator = params.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next();
FormBodyPart field = new FormBodyPart(key, new StringBody(params.get(key) + "", Charset.forName("UTF-8")));
entity.addPart(field);
}
}
return entity;
}
/**
* HTTP DELETE请求
*
* @param url
* 请求url路径
* @param personDbCode
* 人脸库编码
* @param headerMap
* 请求头map
* @return 请求结果json字符串
* @throws ClientProtocolException
* @throws IOException
*/
public static String delete(String url, String someParam, Map headerMap) throws ClientProtocolException, IOException {
String jsonStr = null;
HttpDelete httpDelete = new HttpDelete(url + "/" + someParam);
if (null != headerMap && !headerMap.isEmpty()) {
for (String key : headerMap.keySet()) {
httpDelete.setHeader(key, headerMap.get(key));
}
}
// RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(8000).build();
// CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(httpDelete);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
} else {
jsonStr = EntityUtils.toString(entity, "UTF-8");
response.close();
httpClient.close();
throw new IllegalArgumentException(jsonStr);
}
return jsonStr;
}
/**
* 返回响应正文(无乱码)
*
* @param response
* @return String
*/
public static String getResponseString(HttpResponse response) {
HttpEntity entity = response.getEntity();// 响应实体类
StringBuilder result = new StringBuilder();// 响应正文
if (entity != null) {
byte[] bytes = new byte[4096];
int size;
InputStream instream = null;
try {
instream = entity.getContent();
while ((size = instream.read(bytes)) > 0) {
String str = new String(bytes, 0, size, "utf-8");
result.append(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != instream) {
instream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result.toString();
}
public static void main(String[] args) throws URISyntaxException, IOException {
// 测试get请求---无参
// String jsonStr = HttpUtil.get("http://localhost:8080/Test/testGet", null);
// System.out.println(jsonStr);
// 测试get请求---有参<无文件>
// Map map = new HashMap();
// map.put("a", "aaa");
// map.put("b", 666);
// String jsonStr = HttpUtil.get("http://localhost:8080/Test/testGetAndParam", map);
// System.out.println(jsonStr);
// 测试put请求---无参
// String jsonStr = HttpUtil.put("http://localhost:8080/Test/testPut", null);
// System.out.println(jsonStr);
// 测试put请求---有参<无文件>
// Map map = new HashMap();
// map.put("a", "aaa");
// map.put("b", 666);
// String jsonStr = HttpUtil.put("http://localhost:8080/Test/testPutAndParam", map);
// System.out.println(jsonStr);
// 测试post请求---无参
// String jsonStr = HttpUtil.postUrl("http://localhost:8080/Test/testPost", null);
// System.out.println(jsonStr);
// 测试post请求---有参<无文件>
// Map map = new HashMap();
// map.put("a", "aaa");
// map.put("b", 666);
// String jsonStr = HttpUtil.post("http://localhost:8080/Test/testPostAndParam", map, null, null);
// System.out.println(jsonStr);
// 测试post请求---有参<有文件>
// Map map = new HashMap();
// map.put("a", "aaa");
// map.put("b", 666);
// String jsonStr = HttpUtil.post("http://localhost:8080/Test/testPostAndParamAndFile", map, new File("C:/Users/DaiHaijiao/Pictures/ll.jpg"), "imgFile");
// System.out.println(jsonStr);
}
}