Android中的HTTP通信:
1.什么是HTTP:
HTTP(Hypertext Transfer Protocol)超文本传输协议,在TCP/IP体系结构中,位于应用层。
设计HTTP最初的目的是为了提供一种发布和接受HTML页面的方法。
2.为什么用HTTP
HTTP协议是互联网上应用最为广泛的一种网络协议,
万维网客户端和服务器之间交互需要严格遵守此协议。
3.Android中,怎么用
Android中提供3种HTTP通讯接口:
·标准的JAVA接口(java.net)
·Apache接口(org.apache.http)
·Anroid网络接口(android.net.http)
其中Apache接口提供了更加丰富,高效的工具包。
Apache接口(客户端)
·DefaultHttpClient
·HttpGet
·HttpPost·HttpResponse
以下通过HttpClient接口来简单介绍下,android中的HTTP通信。其中分为GET方式和POST方式两种:
GET方式:
//http地址
String url = "http://192.168.0.101:8080/index.jsp?=HttpClient_Get";
//HttpGet连接对象
HttpGet httpRequest = new HttpGet(url);
//取得HttpClient对象
HttpClient httpclient = new DefaultHttpClient();
//请求HttpClient,获得HttpResponse
try
{
HttpResponse httpresponse = httpclient.execute(httpRequest);
//请求成功
if (httpresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(httpresponse.getEntity());
System.out.println("请求成功"+result);
}
//请求失败
else {
System.out.println("请求失败");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
POST方式:
需要保存要传递的参数以及设置字符集。
//http地址
String url = "http://192.168.0.101:8080/index.jsp?=HttpClient_Get";
//HttpPost连接对象
HttpPost httpRequest = new HttpPost(url);
//使用NameValuePair保存需要传递的POST参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
//添加要传递的参数
params.add(new BasicNameValuePair("pair", "HttpClient_Post"));
//设置字符集
try
{
HttpEntity httpentity = new UrlEncodedFormEntity(params, "utf-8");
//请求httpRequest
httpRequest.setEntity(httpentity);
//取得httpClient对象
HttpClient httpclient = new DefaultHttpClient();
//请求httpClient,获得httpResponse对象
HttpResponse httpresponse = httpclient.execute(httpRequest);
//请求成功
if (httpresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(httpresponse.getEntity());
System.out.println("请求成功"+result);
}
//请求失败
else {
System.out.println("请求失败");
}
}
catch (Exception e)
{
e.printStackTrace();
}