java 发送https请求工具类

java 远程调用 httpclient 调用https接口 忽略SSL认证

httpclient 调用https接口,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。下面是忽略校验过程的代码类:SSLClient**

package com.xiaonuo.ddrepair.util;


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;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;



//用于进行Https请求的HttpClient
@SuppressWarnings("deprecation")
public class SSLClient extends DefaultHttpClient{
	public SSLClient() throws Exception{
        super();
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
                @Override
                public void checkServerTrusted(X509Certificate[] chain,
                        String authType) throws CertificateException {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
        };
        ctx.init(null, new TrustManager[]{tm}, 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));
    }
}

https 请求工具类
上面https 请求工具类 如果不能传参数可参考
HttpPost使用setEntity传递参数传了个寂寞
httpPost.setEntity(param),后台如何取值
HttpClient使用setEntity传递参数 无法获取参数?

如果不想自己写 下面是写好的工具类 可以直接使用

package com.xiaonuo.ddrepair.util;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/*
 * 利用HttpClient进行post请求的工具类
 */
public class HttpClientUtilHttps { // java 发送https   请求
	
	/***
	 * 
	 * @param url       请求路径   https://192.168.196.169:8083/kaitian2/zzd/dologinss
	 * @param map       请求参数   password=111111&username=管理员
	 * @param charset   字符编码   "UTF-8"
	 * @return
	 */

public static String doPost(String url, String map, String charset) {
        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity stringEntity = new StringEntity(map);
     

            stringEntity.setContentEncoding("UTF-8");
            stringEntity.setContentType("application/json");
         
            httpPost.setEntity(stringEntity);
            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;
    }

	
	
	/**
	 * 
	 * @param url       请求路径   https://192.168.196.169:8083/kaitian2/zzd/dologinss
	 * @param map       请求参数     Map<String, String> maps = new HashMap<String, String>();  
	 * @param charset  字符编码   "UTF-8"
	 * @return
	 */
	public static String doPost(String url, Map<String,String> map, String charset) {
        org.apache.http.client.HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;
        try {
            httpClient = new SSLClient();
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator<?> iterator = map.entrySet().iterator();
            
            StringBuilder paramsStr = new StringBuilder();
            while (iterator.hasNext()) {
            	
                @SuppressWarnings("unchecked")
				Map.Entry<String, String> elem = (Map.Entry<String, String>) iterator.next();
             
                //list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
                paramsStr.append(elem.getKey()).append("=").append(elem.getValue()).append("&");
            }
          
            
            if (paramsStr.length() > 0) {
            	
              // UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
               // entity.setContentType("application/json");
               // httpPost.setHeader("Accept", "application/json");
               // httpPost.setHeader("Content-type", "application/json;charset=utf-8");
               // httpPost.setEntity(entity);
                
                
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
                httpPost.setEntity(new StringEntity(paramsStr.substring(0, paramsStr.length() - 1), StandardCharsets.UTF_8));
       
                
            }
            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;
    }
}

测试方法

		Map<String, String> maps = new HashMap<String, String>();  
		//maps.put("username",SM4Utils.decryptData_CBC(name));  
		//maps.put("password",SM4Utils.decryptData_CBC(pwd));  
        maps.put("username","111111");  
		maps.put("password","admin");  
   String strs =HttpClientUtilHttps.doPost("https://192.168.196.169:8083/kaitian2/zzd/dologinss",maps, "UTF-8"); 
System.out.println("https请求 返回内容:"+strs);
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个通用的Java Https请求工具类: ``` import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ConnectException; import java.net.URL; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpsUtil { private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[]{}; } } public static String get(String url) throws Exception { URL u = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) u.openConnection(); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.connect(); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); is.close(); conn.disconnect(); return sb.toString(); } public static String post(String url, String param) throws Exception { URL u = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) u.openConnection(); SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom()); SSLSocketFactory ssf = sslContext.getSocketFactory(); conn.setSSLSocketFactory(ssf); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.connect(); conn.getOutputStream().write(param.getBytes("UTF-8")); InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } br.close(); is.close(); conn.disconnect(); return sb.toString(); } } ``` 这个工具类可以进行Https的GET和POST请求,并且支持自签名证书。使用方法如下: ``` String url = "https://example.com/api"; String result = HttpsUtil.get(url); ``` ``` String url = "https://example.com/api"; String param = "name=value"; String result = HttpsUtil.post(url, param); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值