HttpClient调用远程接口,设置超时

1.先写个工具类:


public class HttpUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpUtil.class);

    public static final String UTF8 = "UTF-8";

    public static String getWithTimeout(final String url,int connectTimeout,int connectionRequestTimeout,int socketTimeout)
            throws  IOException {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom()
                //设置连接超时的时间
                .setConnectTimeout(connectTimeout)
                //设置从连接池里获取连接超时的时间
                .setConnectionRequestTimeout(connectionRequestTimeout)
                //传递数据的超时时间
                .setSocketTimeout(socketTimeout)
                .build();
        httpGet.setConfig(requestConfig);
        return execute(httpclient,httpGet, UTF8);
    }

    private static String execute(final HttpClient httpclient, final HttpUriRequest request, final String charset)
            throws  IOException {
        if (LOGGER.isDebugEnabled()) {

        }

        HttpResponse response = null;
        try {
            response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                int statusCode = response.getStatusLine().getStatusCode();

                String body = EntityUtils.toString(entity, charset);

                if (statusCode == HttpStatus.SC_OK) {
                    return body;
                }
                else {
                    throw new RuntimeException(String.valueOf(statusCode));
                }
            }
            else {
                throw new IOException("get null content for this request");
            }
        }
        catch (ClientProtocolException e) {
            LOGGER.error("ClientProtocolException:{}..{}", request.getProtocolVersion(),e.getMessage());
            throw e;
        }
        finally {
            // httpclient.getConnectionManager().shutdown();

            if (response != null) {
                EntityUtils.consume(response.getEntity()); // 会自动释放连接
            }
        }
    }
}

2.接口中调用:

@GetMapping("/test_http_client")
    public List<String> testHttpClient(int connectTimeout,int connectionRequestTimeout,int socketTimeout){
        String url = "http://192.168.48.151:10188/box_api/integration/2.0/queryRecentlyWatched?uid=19467660";
        List<String> object = null;
        try {
            String result = HttpUtil.getWithTimeout(url, connectTimeout, connectionRequestTimeout, socketTimeout);
            JSONObject jsonObject = JSON.parseObject(result);
            JSONArray data = jsonObject.getJSONArray("data");
            object = JSON.parseArray(JSON.toJSONString(data),String.class);
        } catch (IOException e) {
            log.info("testRest请求超时,uid={}",19467660);
            e.printStackTrace();
        } catch (Exception e){
            e.printStackTrace();
        }
        return object;
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值