Java开发中,经常会需要访问网络资源,一般都是使用http协议去进行访问。进行网络访问最简单的方式就是使用apache提供的HttpClients包。在该篇博客中,我会来实现使用HttpClients来进行GET请求和POST请求。
下面是使用GET请求访问"http://www.baidu.com"网站:
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet("http://www.baidu.com");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容
System.out.println("返回内容: " + EntityUtils.toString(entity));
}
} finally {
response.close();
}
} catch (java.io.IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}下面的代码同样是对同一个url进行POST请求:
public void post() {
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost,也可以把参数放入url中
HttpPost httppost = new HttpPost("http://www.baidu.com");
// 创建参数队列,以键值对的形式存储
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("phone", "1"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
//POST请求可以通过以下的方式把参数放到body中
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}在熟练使用HttpClients后,如果其他系统也提供有RESTful的接口,则我们可以非常方便的调用了。
原文:http://blog.csdn.net/chenyufeng1991/article/details/68961144