当前位置: 首页 > news >正文

java 远程调用 httpclient 调用https接口

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

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

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

相关文章:

  • Jackson 化学发光免疫印迹解决方案
  • GPM 模型剖析【Golang】
  • 将 JavaScript 源文件的全部内容包装在立即调用的函数中的原因是什么?
  • #pragma pack(1)
  • 联动枚举设计
  • 视频批量添加透明水印,必须用这个方法
  • JS获取/修改文本框输入的内容value,修改div标签中的内容:innerHTML、innerTest
  • 我的世界Minecraft Java开服教程(Windows)开服器开服包下载开服网站服务器开服核心开服端开服软件mac版Java启动器资源包
  • java计算机毕业设计物业管理系统源码+系统+数据库+lw文档+mybatis+运行部署
  • Linux下把Tomcat做成服务,并开机自启(方式2-systemctl)
  • java计算机毕业设计西宁市农副产品物流信息系统源码+系统+数据库+lw文档+mybatis+运行部署
  • Python高校学生档案管理系统毕业设计源码071528
  • ​Linux·i2c驱动架构​
  • git代码仓库更换
  • SS【1】:转置卷积与膨胀卷积
  • #Java异常处理
  • 【Leetcode】104. 二叉树的最大深度
  • ➹使用webpack配置多页面应用(MPA)
  • CentOS 7 防火墙操作
  • Java超时控制的实现
  • leetcode378. Kth Smallest Element in a Sorted Matrix
  • mysql常用命令汇总
  • Shell编程
  • Spring Cloud(3) - 服务治理: Spring Cloud Eureka
  • vue自定义指令实现v-tap插件
  • 阿里云ubuntu14.04 Nginx反向代理Nodejs
  • 电商搜索引擎的架构设计和性能优化
  • 基于webpack 的 vue 多页架构
  • 前端相关框架总和
  • 手机app有了短信验证码还有没必要有图片验证码?
  • 小程序上传图片到七牛云(支持多张上传,预览,删除)
  • 新手搭建网站的主要流程
  • 翻译 | The Principles of OOD 面向对象设计原则
  • ​​​​​​​​​​​​​​汽车网络信息安全分析方法论
  • ​总结MySQL 的一些知识点:MySQL 选择数据库​
  • #常见电池型号介绍 常见电池尺寸是多少【详解】
  • (12)Linux 常见的三种进程状态
  • (2022版)一套教程搞定k8s安装到实战 | RBAC
  • (4)logging(日志模块)
  • (html转换)StringEscapeUtils类的转义与反转义方法
  • (Matlab)使用竞争神经网络实现数据聚类
  • (ZT)北大教授朱青生给学生的一封信:大学,更是一个科学的保证
  • (附源码)springboot车辆管理系统 毕业设计 031034
  • (附源码)ssm失物招领系统 毕业设计 182317
  • (附源码)计算机毕业设计SSM疫情社区管理系统
  • (附源码)小程序儿童艺术培训机构教育管理小程序 毕业设计 201740
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (牛客腾讯思维编程题)编码编码分组打印下标题目分析
  • (七)理解angular中的module和injector,即依赖注入
  • (十)c52学习之旅-定时器实验
  • (四)Android布局类型(线性布局LinearLayout)
  • (原+转)Ubuntu16.04软件中心闪退及wifi消失
  • *p++,*(p++),*++p,(*p)++区别?
  • .MSSQLSERVER 导入导出 命令集--堪称经典,值得借鉴!
  • .net core 3.0 linux,.NET Core 3.0 的新增功能