当前位置 : 主页 > 编程语言 > java >

HttpClient请求,只请求一次,不做重试

来源:互联网 收集:自由互联 发布时间:2021-06-28
HttpClient请求 /** * 请求,只请求一次,不做重试 * * @param url 请求的地址 * @param data 提交的数据 * @param connectTimeoutMs 连接超时时间 * @param readTimeoutMs 读取超时时间 * @return * @throws Exception
HttpClient请求
/**
     * 请求,只请求一次,不做重试
     *
     * @param url   请求的地址
     * @param data  提交的数据
     * @param connectTimeoutMs 连接超时时间
     * @param readTimeoutMs 读取超时时间
     * @return
     * @throws Exception
     */
    public String requestOnce(String url, String data, int connectTimeoutMs, int readTimeoutMs) throws Exception {
        BasicHttpClientConnectionManager connManager;
        //设置连接管理器,BasicHttpClientConnectionManager对象线程安全,每次只管理一个连接
        connManager = new BasicHttpClientConnectionManager (
                RegistryBuilder.
 
  create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );

        //构建客户端
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();

        HttpPost httpPost = new HttpPost(url);

        //设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
        httpPost.setConfig(requestConfig);

        //设置请求头和请求数据编码格式
        StringEntity postEntity = new StringEntity(data, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)");
        httpPost.setEntity(postEntity);

        //发送请求,接收请求数据,将请求数据转为string
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        return EntityUtils.toString(httpEntity, "UTF-8");

    }
 
网友评论