首页 > 代码库 > HttpClient访问网络

HttpClient访问网络

HttpClient项目时Apache提供用于访问网络的类,对访问网络的方法进行了封装。在HttpURlConnection类中的输入输出操作,统一封装成HttpGet、HttpPost、HttpResponse

一、服务器端前台

1、发送GET请求的步骤:

(1)创建HttpClient对象:HttpClient httpClient=new DefaultHttpClient();

(2)创建HttpGet对象:HttpGet httpGet=new HttpGet(http://www.baidu.com);

(3)添加发送参数:httpGet.setParams("姑娘的眼睛真大,好漂亮咯!");

(4)调用HttpClient对象的execute()方法发送请求:

HttpResponse httpResponse=httpClient.execute();

例子:

HttpClient httpClient=new DefaultHttpClient();

HttpGet httpGet=new HttpGet(http://www.iciba.com);

httpGet.setParams("真棒!");

tyr{

HttpResponse httpResponse=httpClient.execute();

//判断服务器是否响应

if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){

result=EntityUtils.toString(httpResponse.getEntiry());//获取返回的字符串

}else{result="请求失败!";}

}catch(ClientProtocolException e){

e.printStackTrace();

}catch(IOException e){e.printStackTrace();};

 

HttpClient访问网络