简介:
我们知道在Android上面,支持Socket ,HttpURLConnection(java自带的),HttpClient(apache实现的),这三种基本的数据通信的方式,HttpClient提供了较多的HTTP操作的实现,Android官方推荐使用。
目前,我们常用的HTTP的Method有两个POST个GET,在各种资料上面都有很很多简单的介绍。本文对其简单的介绍一个小小的补充。
官方说明:
- Quick Start - 一个简单、完整的例子包含带参数的HTTP GET和POST。
- HttpClient Tutorial - gives a detailed examination of the HttpClient API, which was written in close accordance with the (sometimes not very intuitive) HTTP specification/standard. A copy is also shipped with the release. A PDF version is also available
- HttpClient Examples - 几个较为复杂的例子。
- HttpClient Primer - explains the scope of HttpClient. Note that HttpClient is not a browser. It lacks the UI, HTML renderer and a JavaScript engine that a browser will possess.
以下是 SOAP 1.2 请求和响应示例。所显示的占位符需替换为实际值。
POST /NourMSWS.asmx HTTP/1.1 Host: 202.xxx.xx.xxx Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <GetDBtime xmlns="http://NourMS.WS.pumoto.com/"> <WSID>string</WSID> <WSPwd>string</WSPwd> </GetDBtime> </soap12:Body> </soap12:Envelope>
返回结果:
HTTP/1.1 200 OK Content-Type: application/soap+xml; charset=utf-8 Content-Length: length <?xml version="1.0" encoding="utf-8"?> <soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"> <soap12:Body> <GetDBtimeResponse xmlns="http://NourMS.WS.pumoto.com/"> <GetDBtimeResult> <ResultType>boolean</ResultType> <ResultInfo>string</ResultInfo> <ResultDsXML>string</ResultDsXML> <TotalNums>int</TotalNums> </GetDBtimeResult> </GetDBtimeResponse> </soap12:Body> </soap12:Envelope>
我们必须对HTTP的头数据添加一些数据和HTTP 协议上添加一个实体数据,如上面的实体XML。
(PS:在平常我们看到的例子中,只有UrlEncodedFormEntity,然而,请求的数据各式各样,google了都没找到,结果都是发送键值对的请求数据,最后在其HttpEntity 的子类上看见StringEntity ,)
具体的实现(代码比较猥琐):
HttpPost httpPost=new HttpPost(url);
HttpClient httpClient=new DefaultHttpClient();
httpPost.addHeader("Content-Type", "application/soap+xml; charset=utf-8");//HTTP 请求是附加的头信息
HttpEntity entity=new StringEntity(httpbody);//post 一段实体数据
System.out.println(httpbody);
httpPost.setEntity(entity);
HttpResponse respons=httpClient.execute(httpPost);
String content = null;
if (respons.getStatusLine().getStatusCode()==HttpStatus.SC_OK) {
// System.out.println();
content=EntityUtils.toString(respons.getEntity());
System.out.println(content);
}
其中,我们看到了 StringEntity 数据,文件上传可以用下面的(更多详细的例子,可以参照 http://hc.apache.org/index.html)。
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
参考:
http://hc.apache.org/index.html
.....sdk/docs/reference/org/apache/http/HttpEntity.html
....sdk/docs/reference/org/apache/http/entity/package-summary.html