V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
amrl
V2EX  ›  问与答

想请教一下各位 V 友这 http 请求问题

  •  
  •   amrl · 2022-07-30 02:35:49 +08:00 · 731 次点击
    这是一个创建于 664 天前的主题,其中的信息可能已经有所发展或是发生改变。
    public static String post(String url, Map<String, String> paramMap, String charset) {
    CloseableHttpClient httpClient = PoolingHttpClientFactory.getInstance().createHttpClient(); //创建实例对象
    HttpPost httpPost = new HttpPost(url);

    CloseableHttpResponse response = null;
    try {
    httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    Iterator<Map.Entry<String, String>> it = paramMap.entrySet().iterator();
    while (it.hasNext()) {
    Map.Entry<String, String> entry = it.next();
    nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));

    // //设置连接 /读取超时时间
    // RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).build();//设置请求和传输超时时间
    // httpPost.setConfig(requestConfig);
    response = httpClient.execute( httpPost);
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(response.getEntity(), "UTF-8");
    // String result = EntityUtils.toString(entity);
    // EntityUtils.consume(entity);
    return result;
    } catch (Exception e) {
    log.error(e.getMessage(), e);
    } finally {

    if (null != response) {
    try {
    response.close();

    } catch (IOException e) {
    log.error(e.getMessage(), e);
    }
    }

    return null;
    }

    这是原代码,在在 finally 下面加上这几个会不会好点,因为线上环境进程线程假死或者直接返回 Http Request Invalid 不知道是不是这个方法写的有问题还是请求的服务器抗不住并发

    if( httpClient != null){
    try {
    httpClient.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    if (null != response) {
    try {
    httpPost.clone();
    } catch (CloneNotSupportedException e) {
    throw new RuntimeException(e);
    }
    }
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   4967 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 08:21 · PVG 16:21 · LAX 01:21 · JFK 04:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.