首页 > 编程语言 >Java中HttpClientUtil工具类

Java中HttpClientUtil工具类

时间:2023-06-04 19:00:49浏览次数:47  
标签:Java String HttpClientUtil static result new httpResponse 工具 httpClient


 HttpClientUtil 包含get和post方法。
发送HttpPost或HttpGet请求一共三个步骤:
1、创建CloseableHttpClient对象,用于执行excute方法
2、创建HttpPost或者HttpGet请求对象
3、执行请求,判断返回状态,接收响应对象

 

 

public class HttpClientUtil {
    /***
     *  编码集
     */
    private final static String CHAR_SET = "UTF-8";
    /***
     *  Post表单请求形式请求头
     */
    private final static String CONTENT_TYPE_POST_FORM = "application/x-www-form-urlencoded";
    /***
     *  Post Json请求头
     */
    private final static String CONTENT_TYPE_JSON = "application/json";
    /***
     *  连接管理器
     */
    private static PoolingHttpClientConnectionManager poolManager;
    /***
     *  请求配置
     */
    private static RequestConfig requestConfig;

    static {
        // 静态代码块,初始化HtppClinet连接池配置信息,同时支持http和https
        try {
            System.out.println("初始化连接池-------->>>>开始");
            // 使用SSL连接Https
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLContext sslContext = builder.build();
            // 创建SSL连接工厂
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            // 初始化连接管理器
            poolManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            // 设置最大连接数
            poolManager.setMaxTotal(1000);
            // 设置最大路由
            poolManager.setDefaultMaxPerRoute(300);
            // 从连接池获取连接超时时间
            int coonectionRequestTimeOut = 5000;
            // 客户端和服务器建立连接超时时间
            int connectTimeout = 5000;
            // 客户端从服务器建立连接超时时间
            int socketTimeout = 5000;
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(coonectionRequestTimeOut)
                    .setConnectTimeout(connectTimeout)
                    .setSocketTimeout(socketTimeout).build();
            System.out.println("初始化连接池-------->>>>结束");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("初始化连接池-------->>>>失败");
        }
    }


    public static String doGet(String url, Map<String, String> params) {
        String result = "";
        // 获取http客户端
        // CloseableHttpClient httpClient = getCloseableHttpClient();
        // 获取http客户端从连接池中
        CloseableHttpClient httpClient = getCloseableHttpClientFromPool();
        // 响应模型
        CloseableHttpResponse httpResponse = null;
        try {
            // 创建URI 拼接请求参数
            URIBuilder uriBuilder = new URIBuilder(url);
            // uri拼接参数
            if (null != params) {
                Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> next = it.next();
                    uriBuilder.addParameter(next.getKey(), next.getValue());
                }
            }
            URI uri = uriBuilder.build();
            // 创建Get请求
            HttpGet httpGet = new HttpGet(uri);
            httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 获取响应实体
                HttpEntity httpEntity = httpResponse.getEntity();
                if (null != httpEntity) {
                    result = EntityUtils.toString(httpEntity, CHAR_SET);
                    System.out.println("响应内容:" + result);
                    return result;
                }
            }
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            System.out.println("响应码:" + statusCode);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != httpResponse) {
                    httpResponse.close();
                }
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private static CloseableHttpClient getCloseableHttpClient() {
        return HttpClientBuilder.create().build();
    }

    /**
     * 从http连接池中获取连接
     */
    private static CloseableHttpClient getCloseableHttpClientFromPool() {
        //
        ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new ServiceUnavailableRetryStrategy() {
            @Override
            public boolean retryRequest(HttpResponse httpResponse, int executionCount, HttpContext httpContext) {
                if (executionCount < 3) {
                    System.out.println("ServiceUnavailableRetryStrategy");
                    return true;
                } else {
                    return false;
                }
            }
            // 重试时间间隔
            @Override
            public long getRetryInterval() {
                return 3000L;
            }
        };
        // 设置连接池管理
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poolManager)
                // 设置请求配置策略
                .setDefaultRequestConfig(requestConfig)
                // 设置重试次数
                .setRetryHandler(new DefaultHttpRequestRetryHandler()).build();
        return httpClient;

    }


    /**
     * Post请求,表单形式
     */
    public static String doPost(String url, Map<String, String> params) {
        String result = "";
        // 获取http客户端
        CloseableHttpClient httpClient = getCloseableHttpClient();
        // 响应模型
        CloseableHttpResponse httpResponse = null;
        try {
            // Post提交封装参数列表
            ArrayList<NameValuePair> postParamsList = new ArrayList<>();
            if (null != params) {
                Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> next = it.next();
                    postParamsList.add(new BasicNameValuePair(next.getKey(), next.getValue()));
                }
            }
            // 创建Uri
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(postParamsList, CHAR_SET);
            // 设置表达请求类型
            urlEncodedFormEntity.setContentType(CONTENT_TYPE_POST_FORM);
            HttpPost httpPost = new HttpPost(url);
            // 设置请求体
            httpPost.setEntity(urlEncodedFormEntity);
            // 执行post请求
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(httpResponse.getEntity(), CHAR_SET);
                //System.out.println("Post form reponse {}" + result);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                CloseResource(httpClient, httpResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    private static void CloseResource(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) throws IOException {
        if (null != httpResponse) {
            httpResponse.close();
        }
        if (null != httpClient) {
            httpClient.close();
        }
    }

    /***
     *  Post请求,Json形式
     */
    public static String doPostJson(String url, String jsonStr) {
        String result = "";
        CloseableHttpClient httpClient = getCloseableHttpClient();
        CloseableHttpResponse httpResponse = null;
        try {
            // 创建Post
            HttpPost httpPost = new HttpPost(url);
            // 封装请求参数
            StringEntity stringEntity = new StringEntity(jsonStr, CHAR_SET);
            // 设置请求参数封装形式
            stringEntity.setContentType(CONTENT_TYPE_JSON);
            httpPost.setEntity(stringEntity);
            httpResponse = httpClient.execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(httpResponse.getEntity(), CHAR_SET);
                System.out.println(result);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                CloseResource(httpClient, httpResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        // get 请求
        //String getUrl = "https://www.baidu.com/s";
        //String getUrl = "http://localhost:9888/boxes/getprojectdaystats";
        //String getUrl = "https://gw.alipayobjects.com/os/antvdemo/assets/data/algorithm-category.json";
        //Map m = new HashMap();
        //  m.put("year","2023");
        // m.put("age","123");
        //String result = doGet(getUrl,m );
        //  System.out.println("result = " + result);

        //Post 请求  baocuo
        // String postUrl = "http://localhost:8088/device/factmag/getInfo";
        // Map m = new HashMap();
        //m.put("Authorization","Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjNkNmI3ZTFjLTU0ZjgtNGE2NS1iMTY1LTE2NjczYzM1MWIxZiIsInVzZXJuYW1lIjoiYWRtaW4ifQ.AyLfDdY9PjpWInEnaiDUBdJVpStEsP1oheWrxCdRcflzJSWPL2VMFFL2SngTO5S0jrI3uwQBWAsccCOG4hRygg");
        //m.put("facregCode","999999");
        // String s = doPost(postUrl, m);
        //System.out.println("s = " + s);


        //String postJsonUrl = "http://127.0.0.1:8080/testHttpClientUtilPostJson";
     /*   User user = new User();
        user.setUid("123");
        user.setUserName("小明");
        user.setAge("18");
        user.setSex("男");
         String jsonStr = JSON.toJSONString(user);
        doPostJson(postJsonUrl,jsonStr); */

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

Java中HttpClientUtil工具类_连接池

Java中HttpClientUtil工具类_连接池_02



标签:Java,String,HttpClientUtil,static,result,new,httpResponse,工具,httpClient
From: https://blog.51cto.com/u_15864767/6411847

相关文章

  • Java中HttpClientUtil工具类
    ​ HttpClientUtil包含get和post方法。发送HttpPost或HttpGet请求一共三个步骤:1、创建CloseableHttpClient对象,用于执行excute方法2、创建HttpPost或者HttpGet请求对象3、执行请求,判断返回状态,接收响应对象  publicclassHttpClientUtil{/****编码集......
  • Java中HttpClientUtil工具类
    ​ HttpClientUtil包含get和post方法。发送HttpPost或HttpGet请求一共三个步骤:1、创建CloseableHttpClient对象,用于执行excute方法2、创建HttpPost或者HttpGet请求对象3、执行请求,判断返回状态,接收响应对象  publicclassHttpClientUtil{/****编码集......
  • kettle 工具数据不正常插入输出的表
    创建表连接时,选择了一个数据库,却能看到所有数据库的表;创建了表输入→表输出,运行之后没有提示任何错误,查看步骤,能看到读取正常,写入却一直在读秒;这个就是数据库插件版本不对,kettle工具需要在lib文件夹下添加和数据库版本对应版本的连接插件 ;......
  • nodejs调试工具
    Node应用调试工具debugger文档 http://nodejs.org/api/debugger.html内置的调试工具,支持基本的断点功能NodeInspector主页 https://github.com/node-inspector/node-inspector通过BlinkDeveloperTools提供的网页版JS调试工具来调试Node程序.NodeEclipse主页 http:......
  • 银河麒麟服务器V10 SP3 安装ZooKeeperZookeeper 图形化的客户端工具(ZooInspector)
    服务器zookeeper安装一、软件介绍1、ZooKeeper是一个分布式的,开放源码的分布式应用程序协调服务,是Google的Chubby一个开源的实现,是Hadoop和Hbase的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。2、ZooKeeper的原理......
  • 【转】sqlplus/RMAN/lsnrctl 等工具连接缓慢
    AIX上sqlplus/assysdbarmantarget/或者lsnrctlstart时或者通过sqlplussystem/oracle@orcl这样通过监听连接等方式来登陆时非常慢(LINUX/HP-UX也存在此问题),甚至要5分钟、10分钟左右才能进入。这种问题在排除系统资源如CPU/IO/内存、网络等资源紧张外;经常是因为hostname......
  • Docker安装Java, Apache, Redis, Tomcat, Postgresql, SSH
    [color=red]centos安装Supervisor[/color][url]http://www.alphadevx.com/a/455-Installing-Supervisor-and-Superlance-on-CentOS[/url]网络设定[b][color=darkblue]#创建网络brctladdbrbr0iplinksetdevbr0upipaddradd192.168.2.1/24devbr0#创建容器#......
  • Java实现AWS S3 签名 自定义验证
    前言最近在开发文件存储服务,需要符合s3的协议标准,可以直接接入aws-sdk,本文针对sdk发出请求的鉴权信息进行重新组合再签名验证有效性,sdk版本如下<dependency><groupId>software.amazon.awssdk</groupId><artifactId>s3</artifactId>......
  • Druid使用起步—在javaWeb项目中配置监控
    配置druid监控springjdbc代码[url]http://19950603.blog.51cto.com/9921553/1616566[/url]AliDruid连接池与监控配置[url]http://langmnm.iteye.com/blog/2112099[/url]阿里巴巴Druid配置监控官方:[url]https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatV......
  • Java实现AWS S3 V4 Authorization自定义验证
    前言最近在开发文件存储服务,需要符合s3的协议标准,可以直接接入aws-sdk,本文针对sdk发出请求的鉴权信息进行重新组合再签名验证有效性,sdk版本如下<dependency><groupId>software.amazon.awssdk</groupId><artifactId>s3</artifactId>......