当前位置: 代码网 > it编程>编程语言>Java > java 远程调用 httpclient 调用https接口 忽略SSL认证

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

2024年08月03日 Java 我要评论
httpclient 调用https接口,如果不进行https校验忽略,远程调用就会报错,为了避免需要证书,所以用一个类继承DefaultHttpClient类,忽略校验过程。下面是忽略校验过程的代码类:SSLClient。

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() {
            @override
            public void checkclienttrusted(java.security.cert.x509certificate[] x509certificates, string s) throws certificateexception {
            }
            @override
            public void checkservertrusted(java.security.cert.x509certificate[] x509certificates, string s) throws certificateexception {
            }
            @override
            public 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<string, string> 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<map.entry<string, string>> iterator = headers.entryset().iterator();
                while (iterator.hasnext()){
                    map.entry<string, string> 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<string,object> params, string charset, map<string, string> headers){
        bufferedreader in = null;
        try {
            // 定义httpclient
            httpclient httpclient = new sslclient();
            // 实例化http方法
            httppost httppost = new httppost();

            if (headers != null) {
                iterator<map.entry<string, string>> iterator = headers.entryset().iterator();
                while (iterator.hasnext()){
                    map.entry<string, string> next = iterator.next();
                    httppost.addheader(next.getkey(), next.getvalue());
                }
            }

            httppost.seturi(new uri(url));

            //设置参数
            list<namevaluepair> nvps = new arraylist<namevaluepair>();
            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<string, object> params, string charset, map<string, string> headers){
        httpclient httpclient = null;
        httpget httpget = null;
        string result = null;
        try{
            if(params !=null && !params.isempty()){
                list<namevaluepair> 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<map.entry<string, string>> iterator = headers.entryset().iterator();
                while (iterator.hasnext()){
                    map.entry<string, string> 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<string, object> params, string charset, map<string, string> headers){
        httpclient httpclient = null;
        httpget httpget = null;
        string result = null;
        try{
            if(params !=null && !params.isempty()){
                list<namevaluepair> 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<map.entry<string, string>> iterator = headers.entryset().iterator();
                while (iterator.hasnext()){
                    map.entry<string, string> 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<string, string> 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<map.entry<string, string>> iterator = headers.entryset().iterator();
                while (iterator.hasnext()){
                    map.entry<string, string> 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<string, string> 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<map.entry<string, string>> iterator = headers.entryset().iterator();
                while (iterator.hasnext()){
                    map.entry<string, string> 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<string, string> 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<map.entry<string, string>> iterator = headers.entryset().iterator();
                while (iterator.hasnext()){
                    map.entry<string, string> 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<string,string> param,map<string, string> 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<map.entry<string, string>> iterator = headers.entryset().iterator();
                while (iterator.hasnext()){
                    map.entry<string, string> next = iterator.next();
                    httppost.addheader(next.getkey(), next.getvalue());
                }
            }
            list<namevaluepair> 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<namevaluepair>
     * @throws @title: transformmap
     * @description: 转换post请求参数
     */
    private static list<namevaluepair> transformmap(map<string, string> params) {
        if (params == null || params.size() < 0) {// 如果参数为空则返回null;
            return new arraylist<namevaluepair>();
        }
        list<namevaluepair> paramlist = new arraylist<namevaluepair>();
        for (map.entry<string, string> map : params.entryset()) {
            paramlist.add(new basicnamevaluepair(map.getkey(), map.getvalue()));
        }
        return paramlist;
    }

}

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com