HttpClient 是HttpConnection的增强 (网络访问)
HttpClient需要导入第三方库的jar包:
在当前工程下新建以文件夹,用来存放第三个的jar文件,比如叫做:libs
全选jar包,右击选择buildpath
(1)使用HttpClient采用GET提交访问访问服务器端并得到服务器端返回的数据
//1.实例化HttpClient对象,相当于用户实例化了浏览器对象
HttpClient httpClient=new DefaultHttpClient();
//2.实例化HttpGet对象并指定访问网址,相当于用户实例化了GET请求对象
HttpGet httpGet=new HttpGet(path);
try {
/*
* 3.调用httpClient对象的execute()方法传递请求对象得到响应对象
*
* 本次操作干了两件事:
* 1.将get请求提交到服务器
* 2.得到服务器发送过来的数据
*/
HttpResponsehttpResponse= httpClient.execute(httpGet);
//4.得到服务器的响应码(状态码)
intresponseCode=httpResponse.getStatusLine().getStatusCode();
//如果本次访问服务器端成功
if(responseCode==HttpStatus.SC_OK)
//使用HttpClient访问服务器端也能得到输入流对象
//InputStreaminputStream=httpResponse.getEntity().getContent();
//5.得到服务器端发送过来的数据并封装成HttpEntity对象
HttpEntityhttpEntity=httpResponse.getEntity();
//6.将对象转化成字符串
Stringresult=EntityUtils.toString(httpEntity);
(2)使用HttpClient采用POST提交访问访问服务器端并得到服务器端返回的数据
* @param path
*/
private static voidsendRequestByPost(String path) {
//1.实例化HttpClient对象,相当于用户实例化了浏览器对象
HttpClient httpClient=new DefaultHttpClient();
//2.实例化HttpPost对象并指定访问网址,相当于用户实例化了Post请求对象
HttpPost httpPost=new HttpPost(path);
try {
//3.设置Post请求需要传递的参数
List<NameValuePair>parameters=new ArrayList<NameValuePair>();
parameters.add(newBasicNameValuePair("userName", "张三"));
parameters.add(newBasicNameValuePair("pwd", "123"));
HttpEntityhttpEntityParameter=new UrlEncodedFormEntity(parameters, "UTF-8");
httpPost.setEntity(httpEntityParameter);
/*
* 4.调用httpClient对象的execute()方法传递请求对象得到响应对象
*
* 本次操作干了两件事:
* 1.将postt请求提交到服务器
* 2.得到服务器发送过来的数据
*/
HttpResponsehttpResponse= httpClient.execute(httpPost);
//5.得到服务器的响应码(状态码)
intresponseCode=httpResponse.getStatusLine().getStatusCode();
//如果本次访问服务器端成功
if(responseCode==HttpStatus.SC_OK){
//使用HttpClient访问服务器端也能得到输入流对象
//InputStreaminputStream=httpResponse.getEntity().getContent();
//6.得到服务器端发送过来的数据并封装成HttpEntity对象
HttpEntityhttpEntity=httpResponse.getEntity();
//7.将对象转化成字符串
Stringresult=EntityUtils.toString(httpEntity);