import com.alibaba.fastjson.JSONObject; import org.apache.http.Consts; 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.CloseableHttpResponse; 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.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; 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.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Component; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.IOException; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * rest接口调用 */ @Component public class RestRequest implements Serializable { private static final long serialVersionUID = -7524694638614823508L; /** * get请求 * * @param url 请求地址 * @param headerParams 请求头参数 * @param clazz 返回对象类型 */ public <T> T doGetRequest(String url, Map<String, String> headerParams, Class<T> clazz) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); T result = null; if (null != headerParams && !headerParams.isEmpty()) { for (Map.Entry<String, String> param : headerParams.entrySet()) { httpGet.addHeader(param.getKey(), param.getValue()); } } CloseableHttpResponse response = httpclient.execute(httpGet); int code = response.getStatusLine().getStatusCode(); if (HttpStatus.SC_OK == code) { String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8); try{ result = JSONObject.parseObject(responseStr, clazz); } catch (Exception e){ result = (T) responseStr; } } return result; } /** * post请求 * * @param url 请求地址 * @param headerParams 请求头参数 * @param requestBody 请求参数 * @param clazz 返回对象类型 */ public <T> T doPostRequest(String url, Map<String, String> headerParams, String requestBody, Class<T> clazz) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); T result = null; if (null != headerParams && !headerParams.isEmpty()) { for (Map.Entry<String, String> param : headerParams.entrySet()) { httpPost.addHeader(param.getKey(), param.getValue()); } } if (null != requestBody) { StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); } HttpResponse response = httpclient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8); result = JSONObject.parseObject(responseStr, clazz); } return result; } /** * post请求FormData参数 * * @param url 请求地址 * @param params 请求参数 * @param clazz 返回对象类型 */ public <T> T doPostFormRequest(String url, Map<String, String> params, Class<T> clazz) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); T result = null; if (null != params && !params.isEmpty()) { List<NameValuePair> paraList = new ArrayList<>(); for (Map.Entry<String, String> param : params.entrySet()) { paraList.add(new BasicNameValuePair(param.getKey(), param.getValue())); } UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(paraList, StandardCharsets.UTF_8); httpPost.setEntity(urlEncodedFormEntity); } HttpResponse response = httpclient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8); result = JSONObject.parseObject(responseStr, clazz); } return result; } /** * put请求 * * @param url 请求地址 * @param headerParams 请求头参数 * @param requestBody 请求参数 * @param clazz 返回对象类型 */ public <T> T doPutRequest(String url, Map<String, String> headerParams, String requestBody, Class<T> clazz) throws IOException { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPut httpPut = new HttpPut(url); T result = null; if (null != headerParams && !headerParams.isEmpty()) { for (Map.Entry<String, String> param : headerParams.entrySet()) { httpPut.addHeader(param.getKey(), param.getValue()); } } if (null != requestBody) { StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); httpPut.setEntity(stringEntity); } HttpResponse response = httpclient.execute(httpPut); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8); result = JSONObject.parseObject(responseStr, clazz); } return result; } /** * post请求 * * @param url 请求地址 * @param headerParams 请求头参数 * @param requestBody 请求参数 * @param clazz 返回对象类型 */ public <T> T doPostRequestIgnoreSSL(String url, Map<String, String> headerParams, String requestBody, Class<T> clazz) throws IOException, KeyManagementException, NoSuchAlgorithmException { //忽略证书 X509TrustManager x509TrustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) { // 不验证 } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom()); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build(); HttpPost httpPost = new HttpPost(url); T result = null; if (null != headerParams && !headerParams.isEmpty()) { for (Map.Entry<String, String> param : headerParams.entrySet()) { httpPost.addHeader(param.getKey(), param.getValue()); } } if (null != requestBody) { StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); } HttpResponse response = httpclient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8); result = JSONObject.parseObject(responseStr, clazz); } return result; } public <T> T doPostRequestIgnoreSSL2(String url, Map<String, String> headerParams, String requestBody, Class<T> clazz) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, IOException { TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; //忽略证书 SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() .loadTrustMaterial(null, acceptingTrustStrategy) .build(); SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(csf) .build(); HttpPost httpPost = new HttpPost(url); T result = null; if (null != headerParams && !headerParams.isEmpty()) { for (Map.Entry<String, String> param : headerParams.entrySet()) { httpPost.addHeader(param.getKey(), param.getValue()); } } if (null != requestBody) { StringEntity stringEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); } HttpResponse response = httpclient.execute(httpPost); int code = response.getStatusLine().getStatusCode(); if (code == HttpStatus.SC_OK) { String responseStr = EntityUtils.toString(response.getEntity(), Consts.UTF_8); result = JSONObject.parseObject(responseStr, clazz); } return result; } }
标签:JAVA,请求,headerParams,param,org,apache,import,new,远程 From: https://www.cnblogs.com/guliang/p/17271546.html