提前引入http相关依赖
<!-- http请求相关 --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.6</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpmime</artifactId> <version>4.5.2</version> </dependency>
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请求 * * @see此get请求若无参数,则params传null * * @param url * @param params * @param headerMap * * @return * @throws ParseException * @throws UnsupportedEncodingException * @throws IOException */ public static String get(String url, Map<String, Object> params, Map<String, String> 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请求 * * @see此put请求若无参数,则params传null * * @param url * @param params * @return * @throws ClientProtocolException * @throws IOException */ public static String put(String url, Map<String, Object> 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 * @param params * @return * @throws ParseException * @throws UnsupportedEncodingException * @throws IOException */ private static String getOrPutNewUrl(String url, Map<String, Object> params) throws ParseException, UnsupportedEncodingException, IOException { if (null != params && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(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请求 * * @see此post请求若无参数,则params传null * * @param url * @param params * @param headerMap * @return * @throws ClientProtocolException * @throws IOException */ public static String httpPost(String url, Map<String, Object> params, Map<String, String> 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()) { httpPost.setEntity(new StringEntity(JSONObject.fromObject(params).toString(), "UTF-8")); } 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请求 * * @see此post请求若无参数,则params传null;若无文件,则file和fileKey都传null * * @param url * 请求url * @param params * 请求参数 * @param file * 请求文件 * @param fileKey * 文件对应key,接口通过此key接收文件 * @param headerMap * http请求的header * @return * @throws ClientProtocolException * @throws IOException */ public static String post(String url, Map<String, Object> params, File file, String fileKey, Map<String, String> 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 * @param file * @param fileKey * @return * @throws UnsupportedEncodingException */ private static MultipartEntity postParamsEntry(Map<String, Object> 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<String> 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请求 * * @see此delete请求仅限于宇视接口调用 * * @param url * @param someParam * @return String * @throws ClientProtocolException * @throws IOException */ public static String delete(String url, String someParam, Map<String, String> 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<String, Object> map = new HashMap<String, Object>(); // 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<String, Object> map = new HashMap<String, Object>(); // 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<String, Object> map = new HashMap<String, Object>(); // 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<String, Object> map = new HashMap<String, Object>(); // 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); } }