五二脚本 手机端 m.52jb.net
特色栏目:PHP教程JavaScript正则表达式焦点幻灯片
页面导航:首页 > 手机教程 > Android > 正文内容

Android开发之服务器交互的POST和GET方法

来源:52脚本网发布时间:11-28浏览:810 次
Android网络编程中与服务器交互主要有2中形式,即POST请求和Get请求,下面我们分别来用实例来讲解POST请求和Get请求。

Android上实现这两种请求,主要还是使用apache的http库
GET请求实现如下:

复制代码 代码如下:
////////////get 请求//////////////////
   public void getRequestWeb(View v)
   {
       HttpGet httpGet = new HttpGet("http://www.pan-apps.com");
       HttpClient client = new DefaultHttpClient();
       InputStream inputStream = null;
       try {
       httpResponse = client.execute(httpGet);
       httpEntity = httpResponse.getEntity();
       inputStream = httpEntity.getContent();
       BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
 
           String line = "";
           String result = "";
           while((line = bufferedReader.readLine())!= null){
               result = result + line;
               System.out.println(line);
           }
 
           System.out.println(result);
 
       } catch (Exception e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
       finally{
           try {
               inputStream.close();
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }
 
   }

POST请求实现如下:

复制代码 代码如下:
/////////// post 请求//////////
    public void postRequest(View v) throws ClientProtocolException, IOException
    {
        //post请求
        HttpPost httpPost = new HttpPost("http://218.0.4.4:8080/esoa/login.do");
 
        //构造post请求内容
        NameValuePair nameValuePair1 = new BasicNameValuePair("username","linpan");
        NameValuePair nameValuePair2 = new BasicNameValuePair("password", "123456");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(nameValuePair1);
        nameValuePairs.add(nameValuePair2);
        HttpEntity httpEntity = new UrlEncodedFormEntity(nameValuePairs);
 
        httpPost.setEntity(httpEntity);
 
        //执行post请求
        HttpClient httpClient = new DefaultHttpClient();
        httpResponse = httpClient.execute(httpPost);
 
        //读取返回数据
        httpEntity = httpResponse.getEntity();
        InputStream inputStream  = null;
        inputStream = httpEntity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while((line = bufferedReader.readLine()) != null)
        {
            result = result + line;
            System.out.println(line);
        }
 
        inputStream.close();
 
    }
 
关于我们 - 联系我们 - 广告合作 - 网站地图 - 网站声明

QQ群:153638182  投稿邮箱: 578640261@qq.com  皖ICP备-14005058

严禁网站镜像,否则追究法律责任。未经www.52jb.net 同意,不得转载本网站上所有的源代码。

五二脚本每日更新大量关于网页制作网页特效php编程网站优化源码下载的实例教程。