聲明:本文轉載自新浪微博,非本人所寫
HttpClient 4.3與4.3版本以下版本比較 -
【加入收藏夾】 【打印】 【關閉】 來源: 日期:2015-07-22 22:00:57 點擊量: 282 收藏
網上利用java發送http請求的代碼很多,一搜一大把,有的利用的是java.net.*下的HttpURLConnection,有的用httpclient,而且發送的代碼也分門別類。今天我們主要來說的是利用httpclient發送請求。
httpclient又可分為
- httpclient3.x
- httpclient4.x到httpclient4.3以下
- httpclient4.3以上
不同httpclient版本其請求發送的方式也不一樣,下面來做個歸納
httpclient3.x
HttpClient client = new HttpClient();
// 設置代理服務器地址和端口
// client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
// 使用 GET 方法 ,如果服務器需要通過 HTTPS 連接,那只需要將下面 URL 中的 http 換成 https
HttpMethodmethod = new GetMethod("http://java.sun.com");
// 使用POST方法
// HttpMethod method = new PostMethod("http://java.sun.com");
client.executeMethod(method);
// 打印服務器返回的狀態
System.out.println(method.getStatusLine());
// 打印返回的信息
System.out.println(method.getResponseBodyAsString());
// 釋放連接
method.releaseConnection();
httpclient4.x到httpclient4.3以下
public void getUrl(String url, String encoding) throws ClientProtocolException, IOException {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(instream, encoding));
System.out.println(reader.readLine());
} catch (Exception e) {
e.printStackTrace();
} finally {
instream.close();
}
}
// 關閉連接.
client.getConnectionManager().shutdown();
}
httpclient4.3以上
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public static String getResult(String urlStr) {
CloseableHttpClient httpClient = HttpClients.createDefault();
// HTTP Get請求
HttpGet httpGet = new HttpGet(urlStr);
// 設置請求和傳輸超時時間
// RequestConfig requestConfig =
// RequestConfig.custom().setSocketTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).build();
// httpGet.setConfig(requestConfig);
String res = "";
try {
// 執行請求
HttpResponse getAddrResp = httpClient.execute(httpGet);
HttpEntity entity = getAddrResp.getEntity();
if (entity != null) {
res = EntityUtils.toString(entity);
}
log.info("響應" + getAddrResp.getStatusLine());
} catch (Exception e) {
log.error(e.getMessage(), e);
return res;
} finally {
try {
httpClient.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
return res;
}
}
return res;
}
