0
点赞
收藏
分享

微信扫一扫

CloseableHttpClient设置超时时间demo 未设置默认是2分钟

一葉_code 2024-10-30 阅读 36

# CloseableHttpClient设置超时时间demo 未设置默认是2分钟

import org.apache.http.HttpHeaders;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

# org.apache.httpcomponents:httpclient:4.5.5

# 方法执行代码
            String content = this.toJson(map or object对象转json);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            
            StringEntity stringEntity = new StringEntity(content);
            HttpPost post = new HttpPost(callbackUrlPic);
            post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
            post.setEntity(stringEntity);
            //设置超时时间,未设置默认是2分钟
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(6000).build();
            post.setConfig(requestConfig);

            CloseableHttpResponse response = httpClient.execute(post);
            String res = EntityUtils.toString(response.getEntity());
            //返回值的处理 todo


public static String toJson(Object obj) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error("convert obj to json error. obj="+obj, e);
        }
        return null;
    }

 

举报

相关推荐

0 条评论