使用HttpCilent获取连接拒绝异常,但在使用HttpsURLConnection时则不然

时间:2016-11-07 08:29:00

标签: java apache http

当我使用HttpClient发送请求但我使用HttpUrlConnection时建立连接时,我收到连接拒绝异常。我想使用HttpClient但是无法弄清楚连接重用的原因是什么,因为当我使用HttpUrlConnection时同样适用。

我使用HttpClient时的代码

public static String httpGet(String urlStr) throws IOException {

    HttpClient conn = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(urlStr);
    HttpResponse response = conn.execute(request);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    // Buffer the result into a string
    BufferedReader rd = new BufferedReader(
        new InputStreamReader(response.getEntity().getContent())
    );
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();
    return sb.toString();
}

我使用HttpUrlConnection时的代码

public static String httpGet(String urlStr) throws IOException {
    URL url = new URL(urlStr);
    HttpsURLConnection conn =
         (HttpsURLConnection) url.openConnection();
    System.out.println("connection"+conn.getResponseCode());

    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    // Buffer the result into a string
    BufferedReader rd = new BufferedReader(
          new InputStreamReader(conn.getInputStream())
    );
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = rd.readLine()) != null) {
        sb.append(line);
    }
    rd.close();

    conn.disconnect();
    return sb.toString();
}

0 个答案:

没有答案