当我使用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();
}