`
mmdev
  • 浏览: 12848112 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

Android入门:用HttpClient模拟HTTP的GET和POST请求

 
阅读更多


一、HttpClient介绍


HttpClient是用来模拟HTTP请求的,其实实质就是把HTTP请求模拟后发给Web服务器;

Android已经集成了HttpClient,因此可以直接使用;

注:此处HttpClient代码不只可以适用于Android,也可适用于一般的Java程序;

HTTP GET核心代码:

(1)DefaultHttpClient client = new DefaultHttpClient();
(2)HttpGet get = new HttpGet(String url);//此处的URL为http://..../path?arg1=value&....argn=value
(3)HttpResponse response = client.execute(get); //模拟请求
(4)int code = response.getStatusLine().getStatusCode();//返回响应码
(5)InputStream in = response.getEntity().getContent();//服务器返回的数据


HTTP POST核心代码:

(1)DefaultHttpClient client = new DefaultHttpClient();
(2)BasicNameValuePair pair = new BasicNameValuePair(String name,String value);//创建一个请求头的字段,比如content-type,text/plain
(3)UrlEncodedFormEntity entity = new UrlEncodedFormEntity(List<NameValuePair> list,String encoding);//对自定义请求头进行URL编码
(4)HttpPost post = new HttpPost(String url);//此处的URL为http://..../path
(5)post.setEntity(entity);
(6)HttpResponse response = client.execute(post);
(7)int code = response.getStatusLine().getStatusCode();
(8)InputStream in = response.getEntity().getContent();//服务器返回的数据

二、服务器端代码


服务器端代码和通过URLConnection发出请求的代码不变:




三、Android客户端代码


效果如下:




在AndroidManifest.xml加入:




MainActivity.java





分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics