Apache包是对android联网访问封装的很好的一个包,也是android访问网络最常用的类。

下面分别讲一下怎么用HttpClient实现get,post请求。

1.Get 请求

1
2
3
4
5
HttpGet get = new HttpGet("http://www.baidu.com");
 
HttpClient hClient = new DefaultHttpClient();
 
httpResponse = hClient.execute(get);

  

2.Post 请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Map<String, String> map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
map.put("permission", String.valueOf(permission));
 
 List<NameValuePair> list = new ArrayList<NameValuePair>();
 if(map != null && !map.isEmpty()){
 for(Map.Entry<String, String> entry : map.entrySet()){//迭代器
 //键值对
 NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
 list.add(nameValuePair);
 }
 }
 
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list ,encode);
//使用post方式提交数据
HttpPost post = new HttpPost(path);
post.setEntity(entity);//请求体中
//默认客户端
HttpClient client = httpClient;
 
HttpResponse httpResponse = client.execute(post);

  

3.代码实例:

先是get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
   
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.DefaultHttpClientConnection; 
import org.apache.http.impl.client.DefaultHttpClient; 
   
import android.app.Activity; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
   
public class MainActivity extends Activity { 
   
    private Button requestButton; 
    private HttpResponse httpResponse; 
    private HttpEntity entity; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_main); 
        requestButton = (Button) findViewById(R.id.requestButton); 
           
        requestButton.setOnClickListener(new OnClickListener() { 
               
            public void onClick(View v) { 
                 new Thread(new Downtest()).start(); 
            } 
        }); 
    } 
   class Downtest implements Runnable{ 
   
      public void run() { 
        //生成一个请求对象,请求 
            HttpGet get = new HttpGet("http://www.baidu.com"); 
            //生成一个Http客户端对象 
            HttpClient hClient = new DefaultHttpClient(); 
            //使用Http客户端发送请求对象 
            InputStream inputStream = null; 
            try { 
                httpResponse = hClient.execute(get);//httpResponse返回的响应 
              //返回的响应数据就放在里边                 
                entity = httpResponse.getEntity(); 
                inputStream = entity.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 (ClientProtocolException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } catch (IOException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            }finally{ 
                try{ 
                    inputStream.close(); 
                }catch(Exception e){ 
                    e.printStackTrace(); 
                } 
            } 
     } 
   }  
      
} 

  再是post请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
public class AccountHttpUtils { 
   
    //private static String PATH = "http://192.168.253.1:8088/CallName/servlet/AccountServler"; 
    private static HttpClient httpClient; 
    public AccountHttpUtils(HttpClient httpClient) { 
           this.httpClient = httpClient; 
    } 
   public static String sendHttpClient(String path,Map<String,String> map,String encode){ 
      List<NameValuePair> list = new ArrayList<NameValuePair>(); 
      if(map != null && !map.isEmpty()){ 
          for(Map.Entry<String, String> entry : map.entrySet()){//迭代器 
              //键值对 
              NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue()); 
              list.add(nameValuePair); 
          } 
      } 
      try { 
          //实现将请求的参数封装到表单中, 
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list ,encode); 
        //使用post方式提交数据 
        HttpPost post = new HttpPost(path); 
        post.setEntity(entity);//请求体中 
        //默认客户端 
        HttpClient client = httpClient; 
           
        HttpResponse httpResponse = client.execute(post); 
        if(httpResponse.getStatusLine().getStatusCode() == 200){ 
            HttpEntity httpEntity = httpResponse.getEntity(); 
            InputStream inputStream = httpEntity.getContent(); 
            return changeInputeStream(inputStream, encode); 
        } 
    } catch (UnsupportedEncodingException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
    } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
    } 
        
       return ""; 
   } 
   /**
    * 将一个输入流转换成字符串
    * @param inputStream
    * @param encode
    * @return
    */ 
   private static String changeInputeStream(InputStream inputStream,String encode) { 
       //通常叫做内存流,写在内存中的 
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
        byte[] data = new byte[1024]; 
        int len = 0; 
        String result = ""; 
        if(inputStream != null){ 
            try { 
                while((len = inputStream.read(data))!=-1){ 
                    data.toString(); 
                    outputStream.write(data, 0, len); 
                } 
                //result是在服务器端设置的doPost函数中的 
                result = new String(outputStream.toByteArray(),encode); 
                outputStream.flush(); 
                outputStream.close(); 
                inputStream.close(); 
            } catch (IOException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } 
        } 
        return result; 
    } 
    public static String set(String id,String name,int permission) { 
        // TODO Auto-generated method stub 
        Map<String, String> map = new HashMap<String, String>(); 
        map.put("id", id); 
        map.put("name", name); 
        map.put("permission", String.valueOf(permission)); 
        String result = AccountHttpUtils.sendHttpClient(AbstractHttpUtils.PATH+"servlet/AccountServler", map, "utf-8"); 
        System.out.println("result:"+ result); 
        return result; 
    } 
   
} 

  4.get请求访问的是百度,返回的是百度首页的源代码

post是我的一个小项目中的类

不过结构已经很清晰啦。。。。

android HTTPclient的更多相关文章

  1. Android HttpClient HttpURLConnection相关介绍

    Android HttpClient HttpURLConnection相关介绍 遇到一个问题 在android studio上用HttpClient编写网络访问代码的时候,发现该类无法导入并使用.. ...

  2. cz.msebera.android.httpclient.conn.ConnectTimeoutException: Connect to /192.168.23.1:8080 timed out(Android访问后台一直说链接超时)

    明明之前还是可以运行的练习,过段时间却运行不了,一直说访问后台超时, 对于这个问题我整整弄了两天加一个晚上,心酸...,上网找了很多但是都解决不了,我就差没有砸电脑了. 首先 : 第一步:Androi ...

  3. Android HttpClient post MultipartEntity - Android 上传文件

    转自[http://blog.csdn.net/hellohaifei/article/details/9707089] 在Android 中使用HttpClient,MultipartEntity ...

  4. Android HttpClient GET或者POST请求基本使用方法(转)

    在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务.这里只介绍如何使用HttpCl ...

  5. android httpClient 支持HTTPS的2种处理方式

    摘自: http://www.kankanews.com/ICkengine/archives/9634.shtml 项目中Android https或http请求地址重定向为HTTPS的地址,相信很 ...

  6. Android HttpClient框架get和post方式提交数据(非原创)

    1.fragment_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android& ...

  7. android httpClient 支持HTTPS的访问方式

    项目中Android https请求地址遇到了这个异常,javax.net.ssl.SSLPeerUnverifiedException: No peer certificate,是SSL协议中没有终 ...

  8. 转 Android HttpClient post MultipartEntity - Android 上传文件

    转自  http://blog.csdn.net/hellohaifei/article/details/9707089 在Android 中使用HttpClient,MultipartEntity ...

  9. Android进阶(三)android httpClient 支持HTTPS的访问方式

    项目中Android https请求地址遇到了这个异常(无终端认证): javax.net.ssl.SSLPeerUnverifiedException: No peer certificate 是S ...

随机推荐

  1. cocos2d-x 内存管理浅析

    Cocos2d-x用create创建对象, 这个方法已经被引擎封装成一个宏定义了:CREATE_FUNC, 下面是这个宏定义的实现: #define CREATE_FUNC(__TYPE__) \   ...

  2. gulp学习笔记1-定义

    1.gulp是前端开发过程中对代码进行构建的自动化工具,可以通过它提供的各种插件实现如:预编译(sass&less).压缩.合并.图片精灵等前端的重复操作 2.基于nodeJS,以js编写插件 ...

  3. Android客户端的图形化拖放操作的设计实现

    为什么要拖放?拖放在某些UI交互中可以简化用户操作. 拖放的步骤包括哪些?“Drag and Drop”,拖放,顾名思义,总共就分三步:1, 开始拖起来:2, 正在拖:3, 放下,进行操作:在这三步里 ...

  4. centos 设置永久dns

    最近在折腾一个问题. 由于服务器的带宽是联通5M, 不稳定.而且所处的网络的dns解析貌似老出问题,每隔一定周期解析时间特别长. 于是乎,想在本地做一个dns,这样可以减少dns解析时间,并做些静态配 ...

  5. Ext 下拉列表模糊搜索

    /** * Created by huangbaidong on 2016/9/18. * 楼盘通用Combo组件,支持模糊查询 * 使用案例: * { fieldLabel : '楼盘名称', xt ...

  6. ubuntu安装文件比较工具Meld

    Meld是一款可视化的文件及目录对比(diff) / 合并 (merge) 工具,通过它你可以对两个或三个文件/目录进行对比,并以图形化的方式显示出它们的不同之处,同时还提供编辑及合并功能,另外还支持 ...

  7. Docker configure http proxy

    from: http://stackoverflow.com/questions/23111631/cannot-download-docker-images-behind-a-proxy That' ...

  8. 【微服务】SpringBoot、SpringCloud相关

    深入学习微框架:Spring Boot:   http://www.infoq.com/cn/articles/microframeworks1-spring-boot/ Spring Boot--2 ...

  9. 【GoLang】深入理解slice len cap什么算法? 参数传递有啥蹊跷?

    先上结论 .内置append函数在现有数组的长度 < 时 cap 增长是翻倍的,再往上的增长率则是 1.25,至于为何后面会说. .Go语言中channel,slice,map这三种类型的实现机 ...

  10. ajax与后台交互传输数据的工具类

    public class Result<T> implements Serializable { private static final long serialVersionUID = ...