V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
amrl
V2EX  ›  问与答

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

  •  
  •   amrl · Jul 30, 2022 · 1139 views
    This topic created in 1371 days ago, the information mentioned may be changed or developed.
    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);
    }
    }
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   804 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 21:45 · PVG 05:45 · LAX 14:45 · JFK 17:45
    ♥ Do have faith in what you're doing.