Android中使用HttpGet和HttpPost访问HTTP资源
16lz
2021-01-25
需求:用户登录(name:用户名,pwd:密码)
(一)HttpGet :doGet()方法
//doGet():将参数的键值对附加在url后面来传递
- publicStringgetResultForHttpGet(Stringname,Stringpwd)throwsClientProtocolException,IOException{
- //服务器:服务器项目:servlet名称
- Stringpath="http://192.168.5.21:8080/test/test";
- Stringuri=path+"?name="+name+"&pwd="+pwd;
- //name:服务器端的用户名,pwd:服务器端的密码
- //注意字符串连接时不能带空格
- Stringresult="";
- HttpGethttpGet=newHttpGet(uri);//编者按:与HttpPost区别所在,这里是将参数在地址中传递
- HttpResponseresponse=newDefaultHttpClient().execute(httpGet);
- if(response.getStatusLine().getStatusCode()==200){
- HttpEntityentity=response.getEntity();
- result=EntityUtils.toString(entity,HTTP.UTF_8);
- }
- returnresult;
- }
(二)HttpPost :doPost()方法
//doPost():将参数打包到http报头中传递
- publicStringgetReultForHttpPost(Stringname,Stringpwd)throwsClientProtocolException,IOException{
- //服务器:服务器项目:servlet名称
- Stringpath="http://192.168.5.21:8080/test/test";
- HttpPosthttpPost=newHttpPost(path);
- List<NameValuePair>list=newArrayList<NameValuePair>();
- list.add(newBasicNameValuePair("name",name));
- list.add(newBasicNameValuePair("pwd",pwd));
- httpPost.setEntity(newUrlEncodedFormEntity(list,HTTP.UTF_8));//编者按:与HttpGet区别所在,这里是将参数用List传递
- Stringresult="";
- HttpResponseresponse=newDefaultHttpClient().execute(httpPost);
- if(response.getStatusLine().getStatusCode()==200){
- HttpEntityentity=response.getEntity();
- result=EntityUtils.toString(entity,HTTP.UTF_8);
- }
- returnresult;
- }
-------------------------------------------------------------------------------------------------------
由此我们可知,HttpGet和HttpPost的区别在于前者是将参数在地址中传递,后者是将参数用List传递。
更多相关文章
- 万字长文带你了解最常用的开源 Squid 代理服务器
- Nginx系列教程(一)| 手把手教你在Linux环境下搭建Nginx服务
- Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
- android 接收SDCcard插拔的广播
- Android下得到APK包含信息
- android Post Get(普通)
- android中的layoutparams参数使用的简单总结
- build.gradle配置参数详解
- Android中MQTT的使用