JAVA利用HttpClient进行POSTGET请求,免证书版本

HTTPS(全称:HyperText Transfer Protocol over Secure Socket Layer),其实 HTTPS 并不是一个新鲜协议,Google 很早就开始启用了,初衷是为了保证数据安全。 近两年,Google、Baidu、Facebook 等这样的互联网巨头,不谋而合地开始大力推行 HTTPS, 国内外的大型互联网公司很多也都已经启用了全站 HTTPS,这也是未来互联网发展的趋势。

 

因为需要特地封装了下

源码下载  

链接:https://pan.baidu.com/s/1Dld7O4d834LftMz2ehSkzA 密码:54fs

视频说明

https://v.qq.com/x/page/u0732zklvh5.html

 

 

如果编译不过,获取缺少包,可以直接下载源码,然后倒入去测试 。

如果还有不明白的,可以加我微 258032791 

 

Main 类源码如下 

package com;

import java.util.HashMap;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    
        
        doPost();
        doGet();
    }
    
    public static void doPost()
    {
        try {
            //创建一个工具类 
            HttpSSLClient sslclient = new HttpSSLClient();
            
            
            //提交的地址 
            String posturl = "https://www.heimataoke.com/login-register";

            
            //设置数据包头 
            HashMap<String ,String> headers = new HashMap<String ,String>();
            
            headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            headers.put("Content-Type","application/x-www-form-urlencoded");
            headers.put("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36");
            
            
            
            //组织提交数据 
            HashMap< String, String> keyvalue = new HashMap<String, String>();
            
            keyvalue.put("username", "13725865412");
            keyvalue.put("qq", "qweqwe");
            keyvalue.put("password", "asdf1234");
            keyvalue.put("repassword", "asdf1234");
            keyvalue.put("agree", "1");
            keyvalue.put("submit", "1");
            //提交数据 
            String result = sslclient.doHttpsPost(posturl, keyvalue, "utf-8", headers);    
            
            
            System.out.printf("Post返回结果 \n%s",result);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void doGet()
    {
        String posturl = "https://www.heimataoke.com/login-register";
        try {
            HttpSSLClient sslclient = new HttpSSLClient();
            String result = sslclient.doHttpsGet(posturl, "utf-8", null);
            System.out.printf("Get返回结果 \n%s",result);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

工具类封装,采用无证书模式 ,

 

package com;

import java.net.URI;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.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.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class HttpSSLClient extends DefaultHttpClient {
    public HttpSSLClient() throws Exception {

        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));
    }

    public static String doHttpsPost(String url, Object postObj, String charset, Map<String, String> headermap) {

        String szRlt = "";
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        HttpResponse response = null;
        try {

            httpClient = new HttpSSLClient();

            URL httpurl = new URL(url);
            URI uri = new URI(httpurl.getProtocol(), httpurl.getHost(), httpurl.getPath(), httpurl.getQuery(), null);

            httpPost = new HttpPost(uri);
            String simpleName = postObj.getClass().getSimpleName();

            // 只列举以下 几个方式

            if (simpleName.equals("HashMap")) {
            
                HashMap<String, String> hm = (HashMap<String, String>) postObj;

                List<NameValuePair> list = new ArrayList<NameValuePair>();
                Iterator iterator = hm.entrySet().iterator();
                while (iterator.hasNext()) {
                    Entry<String, String> elem = (Entry<String, String>) iterator.next();
                    list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
                }
                if (list.size() > 0) {
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                    httpPost.setEntity(entity);
                }
            } else if (simpleName.equals("String")) {
    
                httpPost.setEntity(new StringEntity(postObj.toString(), Charset.forName(charset)));
            } else if (simpleName.equals("MultipartFormEntity")) {
    
                // key value 模式

                httpPost.setEntity((HttpEntity) postObj);
            }

            // 设置头
            if (headermap != null) {

                Iterator it = headermap.entrySet().iterator();
                while (it.hasNext()) {
                    Entry<String, String> elem = (Entry<String, String>) it.next();
                    // elem.getKey();
                    httpPost.addHeader(elem.getKey(), elem.getValue());
                }
            }

            response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {

                    // 获取返回字符串
                    szRlt = EntityUtils.toString(resEntity, "utf-8");
                    httpPost.abort();
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (response != null)
                EntityUtils.consumeQuietly(response.getEntity());
        }

        return szRlt;
    }

    public static String doHttpsGet(String url, String charset, Map<String, String> headermap) {
        String szRlt = "";
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        HttpResponse response = null;
        try {
            httpClient = new HttpSSLClient();
            URL httpurl = new URL(url);
            URI uri = new URI(httpurl.getProtocol(), httpurl.getHost(), httpurl.getPath(), httpurl.getQuery(), null);
            httpGet = new HttpGet(uri);
            HttpParams params = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(params, 5000);
            HttpConnectionParams.setSoTimeout(params, 5000);
            httpGet.setParams(params);
            // 设置头
            if (headermap != null) {
                Iterator it = headermap.entrySet().iterator();
                while (it.hasNext()) {
                    Entry<String, String> elem = (Entry<String, String>) it.next();
                    httpGet.addHeader(elem.getKey(), elem.getValue());
                }
            }
            response = httpClient.execute(httpGet);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {

                    return EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception e) {

            // TODO Auto-generated catch block
            e.printStackTrace();

        } finally {

            if (response != null)
                EntityUtils.consumeQuietly(response.getEntity());
        }
        return "";

    }
}

 

代码写得有些粗糙,但是总算编译通过了,有兴趣可以试试 
 

 


 

            
          

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值