最近在使用httpclient,我也是初学,把一些用法和心得和大家分享下,共同学习,如果使用httpclient 需要依赖httpclient_*.jar 官方下载地址
下载下来将lib下的jar导入工程。
以下代码使用httpclient-4.5.1。
1.使用httpclient 发送Get和Post请求
Get 请求
CloseableHttpClient httpclient = HttpClients.createDefault();
//get 请求
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpGet = new HttpGet("http://www.baidu.com");
System.out.println("Executing get request " + httpGet.getURI());
CloseableHttpResponse response = httpclient.execute(httpGet);
try {
System.out.println(response.getStatusLine()); //返回请求的响应码
httpGet.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
//Post 请求
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("http://www.baidu.com");
List<NameValuePair> pairList = new ArrayList<NameValuePair>();
pairList.add(new BasicNameValuePair("参数名","参数值"));
System.out.println("Executing get request " + httpPost.getURI());
CloseableHttpResponse response = httpclient.execute(httpPost);
try {
System.out.println(response.getStatusLine()); //返回请求的响应码
httpPost.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
转载于:https://blog.51cto.com/7864772/1731407