热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

httpclient常规封装的方法

<dependency><groupId>org.apache.commons<groupId>
       
            org.apache.commons
            commons-compress
            1.18
        
        
            commons-io
            commons-io
            2.4
        
        
            com.relevantcodes
            extentreports
            2.41.1
        
        
            com.vimalselvam
            testng-extentsreport
            1.3.1
        
        
            com.aventstack
            extentreports
            3.0.6
        
        
            com.alibaba
            fastjson
            1.2.47
            compile
        
        
            org.projectlombok
            lombok
            1.16.14
        
        
            org.apache.httpcomponents
            httpclient
            4.5.3
        
package zhihuisystem.HttpClient_Test;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
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.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

public class HttpClient_Utils {
    // 常规get请求
    public static String Getmethod(String url) {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse respons1 = null;
        try {
            respons1 = client.execute(get);
        } catch (ClientProtocolException e1) {
            System.out.println("客户端get请求异常");
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // 切割字符串
        String result = respons1.getStatusLine().toString().split(" ")[1];

        try {
            client.close();// 释放资源
        } catch (IOException e) {
            System.out.println("请求连接无法关闭,关注get方法!");
            e.printStackTrace();
        }
        return result;

    }

    // 常规P0ST请求
    public static String HttpPostWithJson(String url, String json) {

        String returnValue = "这是默认返回值,接口调用失败";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        ResponseHandler respOnseHandler= new BasicResponseHandler();
        try {
            // 创建HttpClient对象
            httpClient = HttpClients.createDefault();
            // 创建httpPost对象
            HttpPost httpPost = new HttpPost(url);
            // 给httpPost设置JSON格式的参数
            StringEntity requestEntity = new StringEntity(json, "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setEntity(requestEntity);
            // 发送HttpPost请求,获取返回值
            returnValue = httpClient.execute(httpPost, responseHandler); // 调接口获取返回值,用此方法
        } catch (Exception e) {
            System.out.println("请求返回值为空!");
            e.printStackTrace();
        }

        finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                System.out.println("请求连接无法关闭,关注post方法!");
                e.printStackTrace();
            }
        }
        // 第五步:处理返回值
        return returnValue;
    }

    // 忽略证书的HTTPS请求 - get
    public static String HttpsGetIgnoreCertification(String url)
            throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException {
        // First create a trust manager that won't care.
        X509TrustManager trustManager = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // Don't do anything.
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // Don't do anything.
            }

            public X509Certificate[] getAcceptedIssuers() {
                // Don't do anything.
                return null;
            }

        };
        // 现在将信任管理器放到SSLContext中。
        SSLContext sslcOntext= SSLContext.getInstance("SSL");
        sslcontext.init(null, new TrustManager[] { trustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, 443));

        HttpGet httpget = new HttpGet(url);
//        String result = "";
        httpget.setHeader("Content-type", "application/json");
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
//        String result1 = response.getStatusLine().toString();
//        String result2 = response.getStatusLine().toString().split(" ")[2];
        String result3 = response.getStatusLine().toString().split(" ")[1];
        return result3;

    }

    // 忽略证书的HTTPS请求 - post
    public static String HttpsPostIgnoreCertification(String url, String requestData)
            throws NoSuchAlgorithmException, KeyManagementException, ClientProtocolException, IOException {
        // First create a trust manager that won't care.
        X509TrustManager trustManager = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // Don't do anything.
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                // Don't do anything.
            }

            public X509Certificate[] getAcceptedIssuers() {
                // Don't do anything.
                return null;
            }

        };
        // 现在将信任管理器放到SSLContext中。
        SSLContext sslcOntext= SSLContext.getInstance("SSL");
        sslcontext.init(null, new TrustManager[] { trustManager }, null);
        SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        DefaultHttpClient httpclient = new DefaultHttpClient();
        httpclient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", sf, 443));

        HttpPost httpPost = new HttpPost(url);
        String result = "";
//            httpPost.setHeader("Authorization", "basic " + "dGNsb3VkYWRtaW46dGNsb3VkMTIz");
        httpPost.setHeader("Content-type", "application/json");
        StringEntity reqEntity;
        // 将请求参数封装成HttpEntity
        reqEntity = new StringEntity(requestData);
        BufferedHttpEntity bhe = new BufferedHttpEntity(reqEntity);
        httpPost.setEntity(bhe);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity resEntity = response.getEntity();
        InputStreamReader reader = new InputStreamReader(resEntity.getContent());
        // 取内存资源
        char[] buff = new char[1024];
        int length = 0;
        while ((length = reader.read(buff)) != -1) {
            result += new String(buff, 0, length);
        }
        httpclient.close();
        return result;

//            System.out.println(result);
    }

    // 启用HTTPS携带证书GET请求
    public static String HttpsforGet(String url, String keystore_PathFile, String keypwd) throws IOException,
            KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = null;
        if (url.startsWith("https")) {
//            "E:\\White_testNG\\mock\\mock_https\\isa\\isa.keystor"
            File cert = new File(keystore_PathFile);
            String keystore = keypwd;
            // Trust own CA and all self-signed certs
            SSLContext sslcOntext= SSLContexts.custom()
                    .loadTrustMaterial(cert, keystore.toCharArray(), new TrustSelfSignedStrategy()).build();
            // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                    null, NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } else {
            httpClient = HttpClients.createDefault();
        }
        try (CloseableHttpClient _httpClient = httpClient; CloseableHttpResponse res = _httpClient.execute(httpGet);) {

            StatusLine sl = res.getStatusLine();
//                System.out.println(sl.toString().split(" ")[1]);
            String result = sl.toString().split(" ")[1];
            /*
             * if (sl != null) { System.out.println(sl.getStatusCode()); StringBuilder
             * builder = new StringBuilder(); try (InputStream is =
             * res.getEntity().getContent(); InputStreamReader isr = new
             * InputStreamReader(is); BufferedReader br = new BufferedReader(isr);) { String
             * line = br.readLine(); while(line != null) { builder.append(line); line =
             * br.readLine(); } System.out.println("响应结果:" + builder.toString());
             */
            return result;
        }
    }

    // 启用HTTPS携带证书post请求
    public static String HttpsforPost(String url, String keystore_PathFile, String keypwd, String json)
            throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException,
            KeyStoreException, CertificateException {

        String returnValue = "这是默认返回值,接口调用失败";
        HttpPost httppost = new HttpPost(url);
        CloseableHttpClient httpClient = null;
        if (url.startsWith("https")) {
            File cert = new File(keystore_PathFile);
            String keystore = keypwd;
            // Trust own CA and all self-signed certs
            SSLContext sslcOntext= SSLContexts.custom()
                    .loadTrustMaterial(cert, keystore.toCharArray(), new TrustSelfSignedStrategy()).build();
            // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                    null, NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } else {
            httpClient = HttpClients.createDefault();
        }
        ResponseHandler respOnseHandler= new BasicResponseHandler();
        try (CloseableHttpClient _httpClient = httpClient; CloseableHttpResponse res = _httpClient.execute(httppost);) {
            StringEntity requestEntity = new StringEntity(json, "utf-8");
            requestEntity.setContentEncoding("UTF-8");
            httppost.setHeader("Content-type", "application/json");
            httppost.setEntity(requestEntity);
            // 发送HttpPost请求,获取返回值
            returnValue = httpClient.execute(httppost, responseHandler); // 调接口获取返回值,用此方法

//                System.out.println(returnValue);

        }
        return returnValue;

    }

}

 


推荐阅读
  • 本文介绍了解决Netty拆包粘包问题的一种方法——使用特殊结束符。在通讯过程中,客户端和服务器协商定义一个特殊的分隔符号,只要没有发送分隔符号,就代表一条数据没有结束。文章还提供了服务端的示例代码。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • 个人学习使用:谨慎参考1Client类importcom.thoughtworks.gauge.Step;importcom.thoughtworks.gauge.T ... [详细]
  • 本文介绍了如何清除Eclipse中SVN用户的设置。首先需要查看使用的SVN接口,然后根据接口类型找到相应的目录并删除相关文件。最后使用SVN更新或提交来应用更改。 ... [详细]
  • (三)多表代码生成的实现方法
    本文介绍了一种实现多表代码生成的方法,使用了java代码和org.jeecg框架中的相关类和接口。通过设置主表配置,可以生成父子表的数据模型。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • Python实现变声器功能(萝莉音御姐音)的方法及步骤
    本文介绍了使用Python实现变声器功能(萝莉音御姐音)的方法及步骤。首先登录百度AL开发平台,选择语音合成,创建应用并填写应用信息,获取Appid、API Key和Secret Key。然后安装pythonsdk,可以通过pip install baidu-aip或python setup.py install进行安装。最后,书写代码实现变声器功能,使用AipSpeech库进行语音合成,可以设置音量等参数。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • Go GUIlxn/walk 学习3.菜单栏和工具栏的具体实现
    本文介绍了使用Go语言的GUI库lxn/walk实现菜单栏和工具栏的具体方法,包括消息窗口的产生、文件放置动作响应和提示框的应用。部分代码来自上一篇博客和lxn/walk官方示例。文章提供了学习GUI开发的实际案例和代码示例。 ... [详细]
  • Java自带的观察者模式及实现方法详解
    本文介绍了Java自带的观察者模式,包括Observer和Observable对象的定义和使用方法。通过添加观察者和设置内部标志位,当被观察者中的事件发生变化时,通知观察者对象并执行相应的操作。实现观察者模式非常简单,只需继承Observable类和实现Observer接口即可。详情请参考Java官方api文档。 ... [详细]
  • mac php错误日志配置方法及错误级别修改
    本文介绍了在mac环境下配置php错误日志的方法,包括修改php.ini文件和httpd.conf文件的操作步骤。同时还介绍了如何修改错误级别,以及相应的错误级别参考链接。 ... [详细]
author-avatar
拍友2502902623
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有