HttpClient
2016-03-04 21:08
495 查看
* 步骤:
1. 创建HttpClient对象
2. 创建HttpGet或者HttpPost对象。将地址传给构造方法。
3. 让HttpClient对象执行请求。得到响应对象HttpResponse
4. 从HttpResponse对象中得到响应码。
5. 判断响应码是否为200,如果200则获得HttpEntity.
6. 用EntityUtils将数据从HttpEntity中获得
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); }
相关文章推荐
- IOS 开发 之 网络编程
- poj3469 Dual Core CPU 网络流 sap邻接表模板
- HttpClient4.5教程-序言
- ATS http — >https
- http://blog.sina.com.cn/s/blog_5b9b4abe01017638.html
- https通讯原理、加密算法、证书整理总结
- HTTPS科普扫盲帖
- 使用PC的adb工具通过wifi(TCP方式)调试安卓设备
- 找工作-——网络IO
- 获取网络gif时候报错 <Error>: ImageIO: _CGImagePluginInitGIF malformed GIF frame#0
- HTTP Live Streaming直播(iOS直播)技术分析与实现
- HTTP协议的学习
- OC-之AFNetworking与ASIHTTPRequest对比
- IHttpModule与IHttpHandler的区别整理
- Android操作HTTP实现与服务器通信
- 记录--java获取网络资源(图片、音频等)保存本地
- Python---TCP编程
- win7下面VM VirtualBox中linux CenOS 网络的配置
- 小笨狼漫谈多线程:GCD(一) http://www.cocoachina.com/ios/20160225/15422.html
- 网络爬虫的实现