httpclient

来源:互联网 发布:人工智能 教育 编辑:程序博客网 时间:2024/06/04 18:25

一,获取httpclient对象,这是操作http协议的入口 HttpClient httpClient=new DefaultHttpClient();

二,得到httppost对象或者get,HttpPost httpPost=new HttpPost(uri); 

三,httpClient.execute(httpPost); 

其实到这里,信息已经发送出去了,如果发送的数据需要携带参数

List<NameValuePair>list=new ArrayList<NameValuePair>(); 

  list.add(new BasicNameValuePair("username",user));  

所有的参数封装在

 UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list, "utf-8"); 

这一步的重要作用是将java对象转换成通用的数据格式,内部可能是调用Json,还有一个作用就是通知服务器所采用的码表


如果服务器端返回了数据

httpClient.execute(httpPost) 取得HttpResponse

要取得数据,最好先判断状态

response.getStatusLine().getStatusCode()==200

然后用一个流进行读取

InputStream inputStream=response.getEntity().getContent();  


Entity包装了几种基本数据类型,是服务器端和客户端交互的翻译,能够将各自对象翻译成共同语言








0 0
原创粉丝点击