CloseableHttpClient简单使用实例[通俗易懂]

importjava.io.BufferedReader;importjava.io.IOException;importjava.nio.charset.Charset;importjava.security.KeyManagementException;importjava.security.KeyStoreException;importjava.security.NoSuchAlgorithmException;importjavax.net.ssl.SSLContext

大家好,又见面了,我是你们的朋友全栈君。

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

import javax.net.ssl.SSLContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.tomcat.util.codec.binary.Base64;

import com.alibaba.fastjson.JSONObject;

/**
 * @author zxs
 *
 */
public class DoubleRecordService extends HttpServlet{

    
    /**
     * 
     */
    private static final long serialVersionUID = 517441780092540387L;
        
    static String httpProtocol = 请求协议;
    static String username = 账号”;
    static String password = 账号对应的密码;(本文使用md5解密后登陆)
    static String ip = “服务地址”;
    static int port = 服务端口; 
    static HttpHost target = null;
    static CloseableHttpClient httpSSlClient = null;
    /**
     * 获取受信任httpClient
     * 
     * @return
     */
    public static CloseableHttpClient createSSLClientDefault() {

        if (target == null)
            target = new HttpHost(ip, port, httpProtocol);
        if (httpSSlClient != null)
            return httpSSlClient;
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(username, GetMD5.GetMD5Code(password)));
        SSLContext sslContext;

        try {

            sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { “TLSv1.2” },
                    null, new NoopHostnameVerifier());
            httpSSlClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(credsProvider)
                    .build();
            return httpSSlClient;
        } catch (KeyManagementException e) {

            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();
        } catch (KeyStoreException e) {

            e.printStackTrace();
        }
        return null;
    }
    
    
    /**
     * @param jsonObject
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String singleCheck(JSONObject jsonObject)
            throws ClientProtocolException, IOException {

        CloseableHttpClient httpclient = createSSLClientDefault();
        String data = null;
        try {

            HttpClientContext localContext = HttpClientContext.create();
            HttpPost httpPost = new HttpPost(httpProtocol + “://” + ip + “:” + port + “/join/singleCheck”);
            System.out.println(httpProtocol + “://” + ip + “:” + port + “/join/singleCheck”);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(50000).setSocketTimeout(50000).build();
            httpPost.setConfig(config);
            httpPost.setHeader(HTTP.TARGET_HOST,”相应ip地址”);
            String body = jsonObject.toJSONString();
            System.out.println(“参数:”+body);
            httpPost.setHeader(“Content-Type”, “application/json”);
            StringEntity stringEntity = new StringEntity(body, “UTF-8”);// 解决中文乱码问题
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, “application/json;charset=utf8”));
            httpPost.setEntity(stringEntity);
            CloseableHttpResponse response = httpclient.execute(target, httpPost, localContext);
            try {

                StatusLine tLine = response.getStatusLine();
                System.out.println(tLine);
                HttpEntity entity = response.getEntity();
                data = IOUtils.toString(entity.getContent(), “UTF-8”);
                System.out.println(data);
            } finally {

                response.close();
            }
        } finally {

//            httpclient.close();
        }
        return data;
    }
    /**
       * 构造Basic Auth认证头信息
       * 
       * @return
       */
    private String getHeader() {

            String auth = username + “:” + GetMD5.GetMD5Code(password);
            byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName(“US-ASCII”)));
            String authHeader = “Basic ” + new String(encodedAuth);
            return authHeader;    
    }
    
}

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

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/127773.html原文链接:https://javaforall.net

(0)
上一篇 2022年4月10日 下午7:40
下一篇 2022年4月10日 下午8:00


相关推荐

  • OpenClaw日志系统配置指南:从基础部署到企业级运维优化

    OpenClaw日志系统配置指南:从基础部署到企业级运维优化

    2026年3月12日
    2
  • runnable 和 callable区别「建议收藏」

    runnable和callable有什么区别?相同点:1、两者都是接口;(废话)2、两者都可用来编写多线程程序;3、两者都需要调用Thread.start()启动线程;不同点:1、两者最大的不同点是:Runnable接口run方法无返回值;Callable接口call方法有返回值。2、Runnable接口run方法只能抛出运行时异常,且无法捕获处理;Callable接口call方法允许抛出异常,可以获取异常信息。注意:Callalbe接口支持返回执行结果,需要调

    2022年4月8日
    50
  • SpringBoot是什么?

    SpringBoot是什么?一、SpringBoot是什么?springboot是spring开源组织下的子项目,是spring组件一站式解决方案,主要是简化了使用spring的难度,节省了繁重的配置,提供了各种启动器,开发者能快速上手。二、SpringBoot的优点1独立运行springboot内嵌了各种servlet容器,Tomcat、Jetty等,现在不再需要打成war包部署到容器中,springboot只要…

    2022年8月20日
    9
  • chkconfig 命令详解

    chkconfig 命令详解功能说明 检查 设定系统的各种服务 语法 chkconfig add del list 系统服务 或 chkconfig level 系统服务 on off reset 补充说明 这个是 redhat 公司遵循 gpl 规则所开发的程序 它可以查询操作系统在每一个执行等级 runlevel 中 会执行哪些系统服务 其中包括各种 daemon linuxo

    2026年3月17日
    2
  • 数据库删除语句[通俗易懂]

    数据库删除语句[通俗易懂]Delete:删除数据表中的行(可以删除某一行,也可以在不删除数据表的情况下删除所有行)。删除某一行:Deletefrom数据表名称where列名称=值;删除所有行:Delete*from数据表名称Drop:删除数据表或数据库,或删除数据表字段。删除数据库:dropdatabase数据库名称删除数据表:(表的结构、属性、索引也会被删除)

    2025年8月19日
    6
  • 面试100题及答案_三特点带你认识基层岗位常见面试题

    面试100题及答案_三特点带你认识基层岗位常见面试题第1期:JS中关闭当前的窗口的方法是:。答案:window.close();第2期:js中使字符串中的字符变为小写的方法是:。答案:toLowerCase方法;第3期:在js中,让浏览器弹出确认框的语句是:。答案:confirm;例如:window.confirm(“我就是确认框”);运行结果是浏览器弹出信息确认框,点击确定,返回true,反之返回false。第4期:把7.25四舍…

    2022年8月27日
    8

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号