zoukankan      html  css  js  c++  java
  • Android之HttpPost与HttpGet使用

    一)HttpGet :doGet()方法
    //doGet():将参数的键值对附加在url后面来传递
            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);
                    //取得HTTP response
                    HttpResponse response=new DefaultHttpClient().execute(httpGet);
                    //若状态码为200
                    if(response.getStatusLine().getStatusCode()==200){
                            //取出应答字符串
                            HttpEntity entity=response.getEntity();
                            result=EntityUtils.toString(entity, HTTP.UTF_8);
                    }
                    return result;
            }
    
    (二)HttpPost :doPost()方法
    //doPost():将参数打包到http报头中传递
            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);
                    //注意:httpPost方法时,传递变量必须用NameValuePair[]数据存储,通过httpRequest.setEntity()方法来发出HTTP请求
                    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));
                   
                    String result="";
                   //取得HTTP response
                    HttpResponse response=new DefaultHttpClient().execute(httpPost);
                    //若状态码为200
                    if(response.getStatusLine().getStatusCode()==200){
                            //取出应答字符串
                            HttpEntity entity=response.getEntity();
                            result=EntityUtils.toString(entity, HTTP.UTF_8);
                    }
                    return result;
            }
  • 相关阅读:
    黑马程序员——用函数实现模块化程序设计(一)
    RN个人笔记SectionListView
    小程序实现APP底部(TabBar)页面控制效果
    #import "项目名-Swift.h"的介绍
    OC & Swift中UITextFiled、UITextView限制输入字数
    Xcode8使用CoreData如何生成OC和Swift版的SubClass
    Swift之“闭包”的应用
    Swift中两种桥接头文件创建方式
    swift头部无线轮播视图
    swift中collectionView的简单用法
  • 原文地址:https://www.cnblogs.com/hyzhou/p/3291361.html
Copyright © 2011-2022 走看看