123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427 |
- package com.yihu.jw.care.util.http;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpStatus;
- import org.apache.http.NameValuePair;
- import org.apache.http.auth.AuthScope;
- import org.apache.http.auth.UsernamePasswordCredentials;
- import org.apache.http.client.CredentialsProvider;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.*;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.BasicCredentialsProvider;
- 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.springframework.util.StringUtils;
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.URL;
- import java.net.URLConnection;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- /**
- * Utils - HTTP请求辅助工具类
- * Created by progr1mmer on 2017/9/27.
- */
- public class HttpUtils {
- public static HttpResponse doGet(String url, Map<String, Object> params) throws Exception {
- return doGet(url, params, null);
- }
- public static HttpResponse doGet(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
- return doGet(url, params, headers, null, null);
- }
- public static HttpResponse doGet(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
- String response;
- int status;
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse closeableHttpResponse = null;
- List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
- if (params != null) {
- for (String key : params.keySet()) {
- Object value = params.get(key);
- if (value != null) {
- nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
- }
- }
- }
- String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
- HttpGet httpGet = new HttpGet(url + "?" + paramStr);
- if (headers != null) {
- for (String key : headers.keySet()) {
- httpGet.addHeader(key, headers.get(key));
- }
- }
- try {
- if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
- UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
- httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
- } else {
- httpClient = HttpClients.createDefault();
- }
- closeableHttpResponse = httpClient.execute(httpGet);
- HttpEntity resEntity = closeableHttpResponse.getEntity();
- status = closeableHttpResponse.getStatusLine().getStatusCode();
- response = getRespString(resEntity);
- } finally {
- try {
- if (closeableHttpResponse != null) {
- closeableHttpResponse.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- }
- if (status != HttpStatus.SC_OK) {
- // LogService.getLogger().error(" GET: " + url + " " + status);
- }
- HttpResponse httpResponse = new HttpResponse(status, response);
- return httpResponse;
- }
- public static HttpResponse doPost(String url, Map<String, Object> params) throws Exception {
- return doPost(url, params, null);
- }
- public static HttpResponse doPost(String url, Map<String, Object> params, Map<String, String> headers) throws Exception{
- return doPost(url, params, headers, null, null);
- }
- public static HttpResponse doPost(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception{
- String response;
- int status;
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse closeableHttpResponse = null;
- HttpPost httpPost = new HttpPost(url);
- List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
- if (params != null) {
- for (String key : params.keySet()) {
- Object value = params.get(key);
- if (value != null) {
- nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
- }
- }
- }
- httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
- if (headers != null) {
- for (String key : headers.keySet()) {
- httpPost.addHeader(key, headers.get(key));
- }
- }
- try {
- if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
- UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
- httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
- } else {
- httpClient = HttpClients.createDefault();
- }
- closeableHttpResponse = httpClient.execute(httpPost);
- HttpEntity resEntity = closeableHttpResponse.getEntity();
- status = closeableHttpResponse.getStatusLine().getStatusCode();
- response = getRespString(resEntity);
- } finally {
- try {
- if (closeableHttpResponse != null) {
- closeableHttpResponse.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- }
- if(status != HttpStatus.SC_OK) {
- // LogService.getLogger().error(" POST: " + url + " " + status);
- }
- HttpResponse httpResponse = new HttpResponse(status, response);
- return httpResponse;
- }
- public static HttpResponse doJsonPost(String url, String jsonData, Map<String, String> headers, String username, String password) throws Exception{
- String response;
- int status;
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse closeableHttpResponse = null;
- HttpPost httpPost = new HttpPost(url);
- httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
- httpPost.setEntity(new StringEntity(jsonData, "UTF-8"));
- if (headers != null) {
- for (String key : headers.keySet()) {
- httpPost.addHeader(key, headers.get(key));
- }
- }
- try {
- if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
- UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
- httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
- } else {
- httpClient = HttpClients.createDefault();
- }
- closeableHttpResponse = httpClient.execute(httpPost);
- HttpEntity resEntity = closeableHttpResponse.getEntity();
- status = closeableHttpResponse.getStatusLine().getStatusCode();
- response = getRespString(resEntity);
- } finally {
- try {
- if (closeableHttpResponse != null) {
- closeableHttpResponse.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- if(status != HttpStatus.SC_OK) {
- // LogService.getLogger().error(" POST: " + url + " " + status);
- }
- HttpResponse httpResponse = new HttpResponse(status, response);
- return httpResponse;
- }
- public static HttpResponse doPut(String url, Map<String, Object> params) throws Exception {
- return doPut(url, params, null);
- }
- public static HttpResponse doPut(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
- return doPut(url, params, headers, null, null);
- }
- public static HttpResponse doPut(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
- String response;
- int status;
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse closeableHttpResponse = null;
- HttpPut httpPut = new HttpPut(url);
- List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
- if (params != null) {
- for (String key : params.keySet()) {
- Object value = params.get(key);
- if (value != null) {
- nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
- }
- }
- }
- httpPut.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
- if (headers != null) {
- for (String key : headers.keySet()) {
- httpPut.addHeader(key, headers.get(key));
- }
- }
- try {
- if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
- UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
- httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
- } else {
- httpClient = HttpClients.createDefault();
- }
- closeableHttpResponse = httpClient.execute(httpPut);
- HttpEntity resEntity = closeableHttpResponse.getEntity();
- status = closeableHttpResponse.getStatusLine().getStatusCode();
- response = getRespString(resEntity);
- } finally {
- try {
- if (closeableHttpResponse != null) {
- closeableHttpResponse.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- if (status != HttpStatus.SC_OK) {
- // LogService.getLogger().error(" PUT: " + url + " " + status);
- }
- HttpResponse httpResponse = new HttpResponse(status, response);
- return httpResponse;
- }
- public static HttpResponse doJsonPut(String url, String jsonData, Map<String, String> headers, String username, String password) throws Exception {
- String response;
- int status;
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse closeableHttpResponse = null;
- HttpPut httpPut = new HttpPut(url);
- httpPut.setHeader("Content-Type", "application/json;charset=UTF-8");
- httpPut.setEntity(new StringEntity(jsonData, "UTF-8"));
- if (headers != null) {
- for (String key : headers.keySet()) {
- httpPut.addHeader(key, headers.get(key));
- }
- }
- try {
- if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
- UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
- httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
- } else {
- httpClient = HttpClients.createDefault();
- }
- closeableHttpResponse = httpClient.execute(httpPut);
- HttpEntity resEntity = closeableHttpResponse.getEntity();
- status = closeableHttpResponse.getStatusLine().getStatusCode();
- response = getRespString(resEntity);
- } finally {
- try {
- if (closeableHttpResponse != null) {
- closeableHttpResponse.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- if (status != HttpStatus.SC_OK) {
- // LogService.getLogger().error(" PUT: " + url + " " + status);
- }
- HttpResponse httpResponse = new HttpResponse(status, response);
- return httpResponse;
- }
- public static HttpResponse doDelete(String url, Map<String, Object> params) throws Exception {
- return doDelete(url, params, null);
- }
- public static HttpResponse doDelete(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
- return doDelete(url, params, headers, null, null);
- }
- public static HttpResponse doDelete(String url, Map<String, Object> params, Map<String, String> headers, String username, String password) throws Exception {
- String response;
- int status;
- CloseableHttpClient httpClient = null;
- CloseableHttpResponse closeableHttpResponse = null;
- List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
- if (params != null) {
- for (String key : params.keySet()) {
- Object value = params.get(key);
- if (value != null) {
- nameValuePairList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
- }
- }
- }
- String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
- HttpDelete httpDelete = new HttpDelete(url + "?" + paramStr);
- if (headers != null) {
- for (String key : headers.keySet()) {
- httpDelete.addHeader(key, headers.get(key));
- }
- }
- try {
- if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
- UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
- CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
- credentialsProvider.setCredentials(AuthScope.ANY, usernamePasswordCredentials);
- httpClient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
- } else {
- httpClient = HttpClients.createDefault();
- }
- closeableHttpResponse = httpClient.execute(httpDelete);
- HttpEntity resEntity = closeableHttpResponse.getEntity();
- status = closeableHttpResponse.getStatusLine().getStatusCode();
- response = getRespString(resEntity);
- } finally {
- try {
- if (closeableHttpResponse != null) {
- closeableHttpResponse.close();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- }catch (Exception e) {
- e.printStackTrace();
- }
- }
- if (status != HttpStatus.SC_OK) {
- // LogService.getLogger().error(" DELETE: " + url + " " + status);
- }
- HttpResponse httpResponse = new HttpResponse(status, response);
- return httpResponse;
- }
- private static String getRespString(HttpEntity entity) throws Exception {
- if (entity == null) {
- return null;
- }
- InputStream is = entity.getContent();
- BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
- StringBuilder stringBuilder = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- stringBuilder.append(line);
- }
- return stringBuilder.toString();
- }
- /**
- * 向指定URL发送GET方法的请求
- *
- * @param url
- * 发送请求的URL
- * @param param
- * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @return URL 所代表远程资源的响应结果
- */
- public String sendLoginGet(String url, String param,String userAgent) {
- String result = "";
- BufferedReader in = null;
- try {
- String urlNameString = url + "?" + param;
- URL realUrl = new URL(urlNameString);
- // 打开和URL之间的连接
- URLConnection connection = realUrl.openConnection();
- // 设置通用的请求属性
- connection.setRequestProperty("accept", "*/*");
- connection.setRequestProperty("connection", "Keep-Alive");
- connection.setRequestProperty("user-agent", userAgent);
- // 建立实际的连接
- connection.connect();
- // 定义 BufferedReader输入流来读取URL的响应
- in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return result;
- }
- }
|