您的位置:首页 > 理论基础 > 计算机网络

HttpClient

2016-03-04 21:08 495 查看
* 步骤:

1. 创建HttpClient对象

2. 创建HttpGet或者HttpPost对象。将地址传给构造方法。

3. 让HttpClient对象执行请求。得到响应对象HttpResponse

4. 从HttpResponse对象中得到响应码。

5. 判断响应码是否为200,如果200则获得HttpEntity.

6. 用EntityUtils将数据从HttpEntity中获得

//创建HttpClient对象--客户端
HttpClient client = new DefaultHttpClient();
//创建请求。---Get:HttpGet
String path = "http://a3.att.hudong.com/36/11/300001378293131694113168235_950.jpg";
HttpGet get = new HttpGet(path);
//让客户端执行请求。得到响应对象
try {
HttpResponse response = client.execute(get);
//得到响应码。:响应码和服务器端发送给客户端的数据都封装在HttpResponse里。
int code = response.getStatusLine().getStatusCode();
if(code==200){
//成功响应。
//得到服务器端的数据。
HttpEntity entity = response.getEntity();
byte[] b = EntityUtils.toByteArray(entity);
//将byte数组的数据写到文件中。
FileOutputStream fos = new FileOutputStream("f:\\a3.jpg");
fos.write(b);
fos.close();
}


//http://localhost:8080/MyServer/login?username=admin&userpwd=111
String path = "http://localhost:8080/MyServer/login";
//1:创建HttpClient
HttpClient client = new DefaultHttpClient();
//2:创建请求。
HttpPost post = new HttpPost(path);
//将数据封装到post对象里。
//创建一个存储封装键值对对象的集合
List<NameValuePair> params = new ArrayList<NameValuePair>();
//将数据封装到NameValuePair对象里,第一个参数为键,第二个参数为值
NameValuePair value1 = new BasicNameValuePair("username", "admin");
NameValuePair value2 = new BasicNameValuePair("userpwd", "1112");
//将对象添加到集合中。
params.add(value1);
params.add(value2);
//将数据集合封装成HttpEntity
HttpEntity entity = new UrlEncodedFormEntity(params);
//设置HttpEntity
post.setEntity(entity);
//让客户端执行请求。
HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if(code==200){
HttpEntity result_entity = response.getEntity();
String str = EntityUtils.toString(result_entity);
System.out.println(str);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: