• Android实现Http协议案例


    在Android开发中,使用Http协议实现网络之间的通信是随处可见的,使用http方式主要采用2中请求方式即get和post两种方式。

    一、使用get方式:

    HttpGet httpGet = new HttpGet(url);
                // 生成一个客户端对象
                httpClient = new DefaultHttpClient();
    
                try {
                    // 通过客户端对象httpClient的execute方法执行请求
                    httpResponse = httpClient.execute(httpGet);
                    httpEntity = httpResponse.getEntity();
                    inputStream = httpEntity.getContent();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(inputStream));
                    String result = "";
                    String line = "";
                    while ((line = reader.readLine()) != null) {
                        result = result + line;
                    }
                    System.out.println(result);
    
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

    二、使用Post方式:

    NameValuePair nameValuePair1 = new BasicNameValuePair("name", name);
                NameValuePair nameValuePair2 = new BasicNameValuePair("age", age);
    
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(nameValuePair1);
                nameValuePairs.add(nameValuePair2);
                try {
                    httpEntity = new UrlEncodedFormEntity(nameValuePairs);
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(httpEntity);
                    httpClient = new DefaultHttpClient();
    
                    try {
                        httpResponse = httpClient.execute(httpPost);
                        httpEntity = httpResponse.getEntity();
                        inputStream = httpEntity.getContent();
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(inputStream));
    
                        String result = "";
                        String line = "";
                        while ((line = reader.readLine()) != null) {
                            result = result + line;
    
                        }
                        System.out.println(result);
    
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            }
  • 相关阅读:
    多点触摸时代来了,第一个是什么呢
    能看出点幻影刺客的风采
    XNA 贴图载入的新状况
    WAR3的模型,幻影刺客,我来了。
    幻影刺客跑起来啦
    TM2T入手
    哥们儿,你终于来了….哈哈,等的花儿都谢了。
    鸣谢 MAGOSX.com
    彩色版幻影刺客留念
    好吧,效果先到这里吧
  • 原文地址:https://www.cnblogs.com/yshuaiw/p/3433566.html
Copyright © 2020-2023  润新知