您的位置:首页 > 理论基础 > 计算机网络

Android平台HttpGet、HttpPost请求实例

2017-06-10 11:54 573 查看

Android客户端请求服务器端的详细解释

1. Android客户端与服务器端通信方式:

Android与服务器通信通常采用HTTP通信方式和Socket通信方式,而HTTP通信方式又分get和post两种方式。

2. 解析服务器端返回数据的解释:

(1).对于服务器端来说,返回给客户端的数据格式一般分为html、xml和json这三种格式。

(2). JSON(Javascript Object Notation)是一种轻量级的数据交换格式,相比于xml这种数据交换格式来说,因为解析xml比较的复杂,而且需要编写大段的代码,所以客户端和服务器的数据交换格式往往通过JSON来进行交换。

3. Android中,用GET和POST访问http资源

(1).客户端向服务器端发送请求的时候,向服务器端传送了一个数据块,也就是请求信息。

(2). GET和POST区别:

A: GET请求请提交的数据放置在HTTP请求协议头(也就是url)中,而POST提交的数据则放在实体数据中,安全性比较高。

B: GET方式提交的数据最多只能有1024字节,而POST则没有此限制。



注意:考虑到POST的优势,在Android开发中自己认为最好用POST的请求方式

HttpGET请求例子:

public String getResultForHttpGet(String name,String pwd) throws ClientProtocolException, IOException{
//服务器  :服务器项目  :servlet名称
String path="http://192.168.5.21:8080/test/test";
String uri=path+"?name="+name+"&pwd="+pwd;
//name:服务器端的用户名,pwd:服务器端的密码
//注意字符串连接时不能带空格

String result="";

HttpGet httpGet=new HttpGet(uri);//编者按:与HttpPost区别所在,这里是将参数在地址中传递
HttpResponse response=new DefaultHttpClient().execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result=EntityUtils.toString(entity, HTTP.UTF_8);
}
return result;
}


HttpPost请求例子:

public String getReultForHttpPost(String name,String pwd) throws ClientProtocolException, IOException{
//服务器  :服务器项目  :servlet名称
String path="http://192.168.5.21:8080/test/test";
HttpPost httpPost=new HttpPost(path);
List<NameValuePair>list=new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("name", name));
list.add(new BasicNameValuePair("pwd", pwd));
httpPost.setEntity(new UrlEncodedFormEntity(list,HTTP.UTF_8));//编者按:与HttpGet区别所在,这里是将参数用List传递

String result="";

HttpResponse response=new DefaultHttpClient().execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
HttpEntity entity=response.getEntity();
result=EntityUtils.toString(entity, HTTP.UTF_8);
}
return result;
}


HttpGet和HttpPost的区别在于前者是将参数在地址中传递,后者是将参数用List传递

异步请求

class GetData extends AsyncTask< String , Integer , String >{

@Override
protected String doInBackground(String... params) {
HttpUtil httpUtil = new HttpUtil() ;
String resutl = httpUtil.httpGet( params[0] ) ;
if( resutl == null ){
return "" ;
}
return resutl ;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: