import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; 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.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * http 工具类 * TODO 改进:httpClient连接池 * @author Zhang */ public final class HttpUtils { private HttpUtils() { throw new AssertionError("不能产生实例"); } private static Logger logger = LoggerFactory.getLogger(HttpUtils.class); /** * 进行get请求 * @param url 访问地址 * @param params 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doGet(String url, String params) throws IOException { return doGet(url, null, params); } /** * 进行get请求 * @param url 访问地址 * @param headers 请求头 * @param params 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doGet(String url, Map<String, String> headers, String params) throws IOException { logger.info("the url is {}", url); logger.info("the request params is {}", params); HttpGet get = new HttpGet(url + '?' + params); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { get.addHeader(entry.getKey(), entry.getValue()); } } try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpResponse res = httpClient.execute(get); int status = res.getStatusLine().getStatusCode(); logger.info("the response status is {}", status); if (status != HttpStatus.SC_OK) { throw new IOException("请求失败,响应码是:" + status); } String resText = EntityUtils.toString(res.getEntity(), "UTF-8"); logger.info("the response is {}", resText); return resText; } finally { get.releaseConnection(); } } /** * 进行get请求 * @param url 访问地址 * @param headers 请求头 * @param params 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws IOException { String query = ""; if (params != null && !params.isEmpty()) { StringBuilder s = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { s.append(entry.getKey()).append('=').append(entry.getValue()).append('&'); } s.setLength(s.length() - 1); query = s.toString(); } return doGet(url, headers, query); } /** * 进行post请求 * @param url 访问地址 * @param params 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doPost(String url, String params, String contentType, String charset) throws IOException { logger.info("the params is {}", params); HttpEntity entity = new StringEntity(params, ContentType.create(contentType, charset)); return doPost(url, entity); } /** * 进行post请求 * @param url 访问地址 * @param params 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doPost(String url, String params) throws IOException { return doPost(url, params, "application/x-www-form-urlencoded", "UTF-8"); } /** * 进行post请求 * @param url 访问地址 * @param params 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doPostJson(String url, String params) throws IOException { return doPost(url, params, "application/json", "UTF-8"); } /** * 进行post请求 * @param url 访问地址 * @param params 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doPost(String url, Map<String, String> params) throws IOException { logger.info("the request params is {}", params); // 添加参数 List<NameValuePair> list = new ArrayList<>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } HttpEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); return doPost(url, entity); } /** * 进行post请求 * @param url 访问地址 * @param entity 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doPost(String url, HttpEntity entity) throws IOException { logger.info("the url is {}", url); HttpPost post = new HttpPost(url); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { post.setEntity(entity); HttpResponse res = httpClient.execute(post); int status = res.getStatusLine().getStatusCode(); logger.info("the response status is {}", status); if (status != HttpStatus.SC_OK) { throw new IOException("请求失败,响应码是:" + status); } String resText = EntityUtils.toString(res.getEntity(), "UTF-8"); logger.info("the response is {}", resText); return resText; } finally { post.releaseConnection(); } } /** * 进行post,提交文件 * @param url 访问地址 * @param params 参数 * @return 响应 * @throws IOException 请求失败 */ public static String doPostFile(String url, Map<String, Object> params) throws IOException { logger.info("the params is {}", params); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); Object obj; // 解决中文乱码 ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8")); for (Map.Entry<String, Object> entry : params.entrySet()) { obj = entry.getValue(); if (obj == null) { continue; } logger.info("the name is {}, the value is {}", entry.getKey(), obj); if (obj instanceof File) { File f = (File) obj; String name = f.getName(); ContentType type; if (name.endsWith(".jpg")) { type = ContentType.create("image/jpg"); } else if (name.endsWith(".png")) { type = ContentType.create("image/png"); } else if (name.endsWith(".jpeg")) { type = ContentType.create("image/jpeg"); } else { type = ContentType.DEFAULT_BINARY; } builder.addBinaryBody(entry.getKey(), f, type, f.getName()); } else if (obj instanceof InputStream) { builder.addBinaryBody(entry.getKey(), (InputStream) obj); } else if (obj instanceof byte[]) { builder.addBinaryBody(entry.getKey(), (byte[]) obj); } else if (obj instanceof String) { builder.addTextBody(entry.getKey(), (String) obj, contentType); } else { builder.addTextBody(entry.getKey(), String.valueOf(obj), contentType); } } return doPost(url, builder.build()); } } |