首页 > 代码库 > android开发,http工具类

android开发,http工具类

android的HttpClient实现简单的get和post请求

[1].[代码] [Java]代码 跳至 [1]

?
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
87
88
/**
 * Http工具类
 */
publicclass HttpUtil {
    // 创建HttpClient对象
    publicstatic HttpClient httpClient = newDefaultHttpClient();
    publicstatic final String BASE_URL = "";
 
    /**
     * get请求
     *
     * @param url
     *            发送请求的URL
     * @return 服务器响应字符串
     * @throws Exception
     */
    publicstatic String doGet(String url) throwsException {
        // 创建HttpGet对象。
        HttpGet get = newHttpGet(url);
        // 发送GET请求
        HttpResponse httpResponse = httpClient.execute(get);
        // 如果服务器成功地返回响应
        if(httpResponse.getStatusLine().getStatusCode() == 200) {
            // 获取服务器响应字符串
            HttpEntity entity = httpResponse.getEntity();
            InputStream content = entity.getContent();
            returnconvertStreamToString(content);
        }
        returnnull;
    }
 
    /**
     * post请求
     *
     * @param url
     *            发送请求的URL
     * @param params
     *            请求参数
     * @return 服务器响应字符串
     * @throws Exception
     */
    publicstatic String doPost(String url, Map<String, String> rawParams)
            throwsException {
        // 创建HttpPost对象。
        HttpPost post = newHttpPost(url);
        // 如果传递参数个数比较多的话可以对传递的参数进行封装
        List<NameValuePair> params = newArrayList<NameValuePair>();
        for(String key : rawParams.keySet()) {
            // 封装请求参数
            params.add(newBasicNameValuePair(key, rawParams.get(key)));
        }
        // 设置请求参数
        post.setEntity(newUrlEncodedFormEntity(params, "utf-8"));
        // 发送POST请求
        HttpResponse httpResponse = httpClient.execute(post);
        // 如果服务器成功地返回响应
        if(httpResponse.getStatusLine().getStatusCode() == 200) {
            // 获取服务器响应字符串
            HttpEntity entity = httpResponse.getEntity();
            InputStream content = entity.getContent();
            returnconvertStreamToString(content);
        }
        returnnull;
    }
 
    /**
     * 获取服务器的响应,转换为字符串
     */
    privatestatic String convertStreamToString(InputStream is) {
        BufferedReader reader = newBufferedReader(newInputStreamReader(is));
        StringBuilder sb = newStringBuilder();
        String line = null;
        try{
            while((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }catch(IOException e) {
            e.printStackTrace();
        }finally{
            try{
                is.close();
            }catch(IOException e) {
                e.printStackTrace();
            }
        }
        returnsb.toString();
    }
}

android开发,http工具类