java 远程调用 httpclient 调用https接口 忽略SSL认证
httpclient 调用https接口,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。下面是忽略校验过程的代码类:SSLClient
package com.pms.common.https;import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;/*** 用于进行Https请求的HttpClient* @ClassName: SSLClient* @Description: TODO**/
public class SSLClient extends DefaultHttpClient {public SSLClient() throws Exception{super();SSLContext ctx = SSLContext.getInstance("TLS");ctx.init(null, getTrustingManager(), null);SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);ClientConnectionManager ccm = this.getConnectionManager();SchemeRegistry sr = ccm.getSchemeRegistry();sr.register(new Scheme("https", 443, ssf));}private static TrustManager[] getTrustingManager() {TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {@Overridepublic void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {}@Overridepublic java.security.cert.X509Certificate[] getAcceptedIssuers() {return null;}} };return trustAllCerts;}
}
然后再调用的远程get、post请求中使用SSLClient 创建Httpclient ,代码如下:
package com.pms.common.https;import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
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.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;public class HttpsClientUtil {/*** post请求(用于请求json格式的参数)* @param url* @param param* @return*/@SuppressWarnings("resource")public static String doHttpsPost(String url, String param, String charset, Map headers){HttpClient httpClient = null;HttpPost httpPost = null;String result = null;try{httpClient = new SSLClient();httpPost = new HttpPost(url);httpPost.addHeader("Content-Type", "application/json");if (headers != null) {Iterator> iterator = headers.entrySet().iterator();while (iterator.hasNext()){Map.Entry next = iterator.next();httpPost.addHeader(next.getKey(), next.getValue());}}StringEntity se = new StringEntity(param);se.setContentType("application/json;charset=UTF-8");se.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));httpPost.setEntity(se);HttpResponse response = httpClient.execute(httpPost);if(response != null){HttpEntity resEntity = response.getEntity();if(resEntity != null){result = EntityUtils.toString(resEntity,charset);}}}catch(Exception ex){ex.printStackTrace();}return result;}/*** post请求(用于key-value格式的参数)* @param url* @param params* @return*/@SuppressWarnings("resource")public static String doHttpsPostKV(String url, Map params, String charset, Map headers){BufferedReader in = null;try {// 定义HttpClientHttpClient httpClient = new SSLClient();// 实例化HTTP方法HttpPost httpPost = new HttpPost();if (headers != null) {Iterator> iterator = headers.entrySet().iterator();while (iterator.hasNext()){Map.Entry next = iterator.next();httpPost.addHeader(next.getKey(), next.getValue());}}httpPost.setURI(new URI(url));//设置参数List nvps = new ArrayList();for (Iterator iter = params.keySet().iterator(); iter.hasNext();) {String name = (String) iter.next();String value = String.valueOf(params.get(name));nvps.add(new BasicNameValuePair(name, value));//System.out.println(name +"-"+value);}httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));HttpResponse response = httpClient.execute(httpPost);int code = response.getStatusLine().getStatusCode();if(code == 200){ //请求成功in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),"utf-8"));StringBuffer sb = new StringBuffer("");String line = "";String NL = System.getProperty("line.separator");while ((line = in.readLine()) != null) {sb.append(line + NL);}in.close();return sb.toString();}else{ //System.out.println("状态码:" + code);return null;}}catch(Exception e){e.printStackTrace();return null;}}@SuppressWarnings("resource")public static String doHttpsGet(String url, Map params, String charset, Map headers){HttpClient httpClient = null;HttpGet httpGet = null;String result = null;try{if(params !=null && !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), charset);}httpClient = new SSLClient();httpGet = new HttpGet(url);
// httpGet.addHeader("Content-Type", "application/json");if (headers != null) {Iterator> iterator = headers.entrySet().iterator();while (iterator.hasNext()){Map.Entry next = iterator.next();httpGet.addHeader(next.getKey(), next.getValue());}}HttpResponse response = httpClient.execute(httpGet);if(response != null){HttpEntity resEntity = response.getEntity();if(resEntity != null){result = EntityUtils.toString(resEntity,charset);}}}catch(Exception ex){ex.printStackTrace();}return result;}//get 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8//带参数@SuppressWarnings("resource")public static String doHttpsFormUrlencodedGetRequest(String url, Map params, String charset, Map headers){HttpClient httpClient = null;HttpGet httpGet = null;String result = null;try{if(params !=null && !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), charset);}httpClient = new SSLClient();httpGet = new HttpGet(url);httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// httpGet.addHeader("Content-Type", "application/json");if (headers != null) {Iterator> iterator = headers.entrySet().iterator();while (iterator.hasNext()){Map.Entry next = iterator.next();httpGet.addHeader(next.getKey(), next.getValue());}}HttpResponse response = httpClient.execute(httpGet);if(response != null){HttpEntity resEntity = response.getEntity();if(resEntity != null){result = EntityUtils.toString(resEntity,charset);}}}catch(Exception ex){ex.printStackTrace();}return result;}//post 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8//带参数@SuppressWarnings("resource")public static String doHttpsFormUrlencodedPostRequest(String url, String param, String charset, Map headers){HttpClient httpClient = null;HttpPost httpPost = null;String result = null;try{httpClient = new SSLClient();httpPost = new HttpPost(url);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");if (headers != null) {Iterator> iterator = headers.entrySet().iterator();while (iterator.hasNext()){Map.Entry next = iterator.next();httpPost.addHeader(next.getKey(), next.getValue());}}StringEntity se = new StringEntity(param);se.setContentType("application/x-www-form-urlencoded;charset=utf-8");se.setContentEncoding(new BasicHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8"));httpPost.setEntity(se);HttpResponse response = httpClient.execute(httpPost);if(response != null){HttpEntity resEntity = response.getEntity();if(resEntity != null){result = EntityUtils.toString(resEntity,charset);}}}catch(Exception ex){ex.printStackTrace();}return result;}//post 请求类型 ContentType: application/x-www-form-urlencoded;charset=UTF-8//不带参数 或者参数拼接在url中public static String doHttpsFormUrlencodedPostNoParam(String url, String charset, Map headers){HttpClient httpClient = null;HttpPost httpPost = null;String result = null;try{
// url = url+URLEncoder.encode("{1}", "UTF-8");httpClient = new SSLClient();httpPost = new HttpPost(url);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");if (headers != null) {Iterator> iterator = headers.entrySet().iterator();while (iterator.hasNext()){Map.Entry next = iterator.next();httpPost.addHeader(next.getKey(), next.getValue());}}HttpResponse response = httpClient.execute(httpPost);if(response != null){HttpEntity resEntity = response.getEntity();if(resEntity != null){result = EntityUtils.toString(resEntity,charset);}}}catch(Exception ex){ex.printStackTrace();}return result;}//传文件到远程post接口public static String sendPostWithFile(String url, String param,Map headers,File file) throws Exception{HttpClient httpClient = null;HttpPost httpPost = null;String result = null;try{MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", new FileBody(file));HttpEntity multipartEntity = builder.build();httpClient = new SSLClient();httpPost = new HttpPost(url);if (headers != null) {Iterator> iterator = headers.entrySet().iterator();while (iterator.hasNext()){Map.Entry next = iterator.next();httpPost.addHeader(next.getKey(), next.getValue());}}httpPost.setEntity(multipartEntity);StringEntity se = new StringEntity(param);
// se.setContentType("multipart/form-data;charset=utf-8");
// se.setContentEncoding(new BasicHeader("Content-Type", "multipart/form-data;charset=utf-8"));httpPost.setEntity(se);HttpResponse response = httpClient.execute(httpPost);//获取接口返回值InputStream is = response.getEntity().getContent();BufferedReader in = new BufferedReader(new InputStreamReader(is));StringBuffer bf = new StringBuffer();String line= "";while ((line = in.readLine()) != null) {bf.append(line);}System.out.println("发送消息收到的返回:"+bf.toString());return bf.toString();}catch(Exception ex){ex.printStackTrace();}return result;}/*** @param @param url* @param @param formParam* @param @param proxy* @param @return* @return String* @throws* @Title: httpPost* @Description: http post请求* UrlEncodedFormEntity Content-Type=application/x-www-form-urlencoded*/public static String httpPostbyFormHasProxy(String url, Map param,Map headers,File file) throws IOException {log.info("请求URL:{}", url);long ls = System.currentTimeMillis();HttpPost httpPost = null;HttpClient httpClient = null;String result = "";try {MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", new FileBody(file));HttpEntity multipartEntity = builder.build();httpPost = new HttpPost(url);if (headers != null) {Iterator> iterator = headers.entrySet().iterator();while (iterator.hasNext()){Map.Entry next = iterator.next();httpPost.addHeader(next.getKey(), next.getValue());}}List paramList = transformMap(param);UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList, "utf8");httpPost.setEntity(formEntity);httpClient = new SSLClient();HttpResponse httpResponse = httpClient.execute(httpPost);int code = httpResponse.getStatusLine().getStatusCode();log.info("服务器返回的状态码为:{}", code);if (code == HttpStatus.SC_OK) {// 如果请求成功result = EntityUtils.toString(httpResponse.getEntity());}}catch (UnsupportedEncodingException e){e.printStackTrace();}catch(Exception ex){ex.printStackTrace();}finally {if (null != httpPost) {httpPost.releaseConnection();}long le = System.currentTimeMillis();log.info("返回数据为:{}", result);log.info("http请求耗时:ms", (le - ls));}return result;}/*** @param @param params* @param @return* @return List* @throws @Title: transformMap* @Description: 转换post请求参数*/private static List transformMap(Map params) {if (params == null || params.size() < 0) {// 如果参数为空则返回null;return new ArrayList();}List paramList = new ArrayList();for (Map.Entry map : params.entrySet()) {paramList.add(new BasicNameValuePair(map.getKey(), map.getValue()));}return paramList;}}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
