Android使用Apache HttpClient发送GET、POST请求

本文详细介绍了如何使用Apache HttpClient进行HTTP请求,包括创建HttpClient对象、发送GET和POST请求、处理响应等内容。通过实例演示了GET和POST请求的实现方式,并提供了错误处理策略。
简单的网页下载,HttpURLConnection可以完成,但是涉及到用户登录等权限相关问题,就需要涉及Session、Cookies。,就很难使用HttpURLConnection来处理了。Apache开源组织提供了一个HttpClient项目可以处理这些问题。HttpClient关注于如何发送请求、接受请求,以及管理HTTP链接。
使用HttpClient对象来发送请求、接受响应步骤:


创建HttpClient对象
如果要发送GET请求,创建HttpGet对象;如果是POST请求,则创建HttpPost对象。
如果需要添加参数,对于HttpGet直接在构造URL的时候填入参数。对于POST请求,使用setEntity(HttpEntity entity)方法来设置
调用HttpClient对象的execute(HttpUriRequest request)发送请求,此方法返回一个HttpResponse
调用HttpResponse的getALLHeaders()、getHeaders(String name)等方法可获取服务器响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器响应内容。
注意:


不少地方说可以使用HttpGet和HttpPost共同的setParams(HttpParams params)方法添加请求参数,但是我没有设置成功,网上搜索发现好多人也没成功。Even Apache’s official example uses URIBuilder’s setParameter method to build the params out in the URI,所以没有使用这种方法.


GET请求Demo:

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textViewShow = (TextView) findViewById(R.id.showText);
        //直接在URL后添加请求参数
        String url = "http://192.168.1.103/index.php?get1=hello&get2=bay";
        try {
            // 创建DefaultHttpClient对象
            HttpClient httpclient = new DefaultHttpClient();
            // 创建一个HttpGet对象
            HttpGet get = new HttpGet(url);
            // 获取HttpResponse对象
            HttpResponse response = httpclient.execute(get);
            //判断是否链接成功
            if (response.getStatusLine().getStatusCode() == 200) {
                //实体转换为字符串
                String content = EntityUtils.toString(response.getEntity(),"utf-8");
                textViewShow.setText(content);
            }else{
                textViewShow.setText("网络错误");
            }
 
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
POST请求Demo:

public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textViewShow = (TextView) findViewById(R.id.showText);
 
        String url = "http://192.168.1.103/index.php";
        HttpClient httpClient = new DefaultHttpClient();
        try {
        HttpPost post = new HttpPost(url);
        List params = new ArrayList();
        params.add(new BasicNameValuePair("get1", "hello"));
        params.add(new BasicNameValuePair("get2", "usrl"));
 
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(post);
            if(response.getStatusLine().getStatusCode() ==200){
                String content = EntityUtils.toString(response.getEntity(),"utf-8");
                textViewShow.setText(content);
 
            }else{
                textViewShow.setText("网络问题");
            }
 
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            textViewShow.setText("UnsupportedEncodingException");
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            textViewShow.setText("ClientProtocolException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            textViewShow.setText("IOException");
        }
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
}



<think> 我们正在使用Apache HttpClient库来发送HTTP请求。根据引用内容,我们可以总结出以下步骤: 1. 创建HttpClient对象。 2. 创建请求对象(HttpGet用于GET请求,HttpPost用于POST请求)。 3. 对于POST请求,可以设置请求体(如JSON数据或表单数据)。 4. 执行请求并获取响应。 5. 从响应中获取状态码和响应内容。 6. 关闭资源。 我们将分别展示发送GETPOST请求的示例代码。 注意:根据引用[5],我们需要添加依赖(如果使用Maven): ```xml <dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.3</version> </dependency> ``` 下面分别给出GETPOST请求的详细步骤和代码示例。 ### 发送GET请求 步骤: 1. 创建`CloseableHttpClient`对象(使用`HttpClients.createDefault()`)。 2. 创建`HttpGet`对象,并传入URL。 3. 使用`HttpClient`对象执行`HttpGet`请求,得到`CloseableHttpResponse`。 4. 从响应中获取状态码和响应实体。 5. 将响应实体转换为字符串。 6. 关闭响应和HttpClient。 示例代码(引用[3]中的示例): ```java public void testGET() throws IOException { // 1. 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 2. 创建请求对象 HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status"); // 3. 发送请求,获取响应 CloseableHttpResponse response = httpClient.execute(httpGet); // 4. 获取状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("服务端返回的状态码为:" + statusCode); // 5. 获取响应内容 HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity); System.out.println("服务端返回的数据为:" + body); // 6. 关闭资源 response.close(); httpClient.close(); } ``` ### 发送POST请求JSON数据) 步骤: 1. 创建`CloseableHttpClient`对象。 2. 创建`HttpPost`对象,并传入URL。 3. 设置请求头(如`Content-Type`为`application/json`)。 4. 构建JSON字符串,并设置到请求体中(使用`StringEntity`)。 5. 执行请求,得到响应。 6. 处理响应(获取状态码和响应内容)。 7. 关闭资源。 示例代码(参考引用[1]和[4]): ```java public void testPOST() throws IOException { // 1. 创建HttpClient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); // 2. 创建HttpPost对象 HttpPost httpPost = new HttpPost("http://example.com/api/resource"); // 3. 设置请求头(JSON类型) httpPost.setHeader("Content-Type", "application/json"); // 4. 构建JSON请求体 String json = "{\"title\":\"foo\", \"body\":\"bar\", \"userId\":1}"; StringEntity entity = new StringEntity(json, StandardCharsets.UTF_8); httpPost.setEntity(entity); // 5. 发送请求,获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); // 6. 获取状态码 int statusCode = response.getStatusLine().getStatusCode(); System.out.println("Response Code: " + statusCode); // 7. 获取响应内容 HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); System.out.println("Response Content: " + responseBody); // 8. 关闭资源 response.close(); httpClient.close(); } ``` ### 发送POST请求(表单数据) 如果需要发送表单数据(application/x-www-form-urlencoded),可以使用`UrlEncodedFormEntity`。 示例代码(参考引用[4]): ```java public void testFormPOST() throws IOException { CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api/form"); // 设置表单参数 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("key1", "value1")); params.add(new BasicNameValuePair("key2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8)); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); System.out.println("Response Code: " + statusCode); HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); System.out.println("Response Content: " + responseBody); response.close(); httpClient.close(); } ``` 注意事项: - 在实际使用中,应该使用try-with-resources来确保资源关闭,避免资源泄漏(Java 7及以上)。 - 可以设置连接超时等配置(引用[4]提到),这里没有展示,但可以通过`RequestConfig`自定义。 下面给出使用try-with-resources的改进版GET请求示例: ```java public void testGETWithTryResources() throws IOException { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet("http://localhost:8080/user/shop/status"); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { int statusCode = response.getStatusLine().getStatusCode(); System.out.println("服务端返回的状态码为:" + statusCode); HttpEntity entity = response.getEntity(); String body = EntityUtils.toString(entity); System.out.println("服务端返回的数据为:" + body); } } } ``` 同理,POST请求也可以使用try-with-resources。 以上便是使用Apache HttpClient发送GETPOST请求的基本方法。 §§相关问题§§ 1. 如何处理使用Apache HttpClient时可能出现的异常? 2. 如何设置Apache HttpClient的连接超时和读取超时? 3. 如何在POST请求发送文件(上传文件)? </think> ### Apache HttpClient 发送 GET/POST 请求方法 #### 一、GET 请求步骤(引用[3]) ```java import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.methods.HttpGet; public void sendGetRequest() throws Exception { // 1. 创建HttpClient对象 try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // 2. 创建HttpGet对象(设置URL) HttpGet httpGet = new HttpGet("http://api.example.com/data"); // 3. 可选:设置请求头 httpGet.setHeader("Accept", "application/json"); // 4. 发送请求并获取响应 try (CloseableHttpResponse response = httpClient.execute(httpGet)) { // 5. 获取状态码 int statusCode = response.getCode(); System.out.println("HTTP状态码: " + statusCode); // 6. 获取响应内容 HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); System.out.println("响应内容: " + responseBody); // 7. 确保资源释放 EntityUtils.consume(entity); } } } ``` #### 二、POST 请求步骤(引用[1][4]) ```java import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse; import org.apache.hc.client5.http.impl.classic.HttpClients; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.io.methods.HttpPost; public void sendPostRequest() throws Exception { // 1. 创建HttpClient对象 try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // 2. 创建HttpPost对象(设置URL) HttpPost httpPost = new HttpPost("http://api.example.com/submit"); // 3. 设置请求头(JSON示例) httpPost.setHeader("Content-Type", "application/json"); // 表单示例:httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 4. 构建请求体 String jsonBody = "{\"name\":\"John\", \"age\":30}"; httpPost.setEntity(new StringEntity(jsonBody)); // JSON数据 /* 表单数据示例: List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("key1", "value1")); httpPost.setEntity(new UrlEncodedFormEntity(params)); */ // 5. 发送请求并处理响应 try (CloseableHttpResponse response = httpClient.execute(httpPost)) { int statusCode = response.getCode(); System.out.println("响应码: " + statusCode); HttpEntity entity = response.getEntity(); System.out.println("响应内容: " + EntityUtils.toString(entity)); EntityUtils.consume(entity); } } } ``` #### 三、关键配置说明 1. **依赖配置**(引用[5]) ```xml <dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.3</version> </dependency> ``` 2. **超时设置**(引用[4]) ```java RequestConfig config = RequestConfig.custom() .setConnectTimeout(5000) // 连接超时 .setSocketTimeout(30000) // 数据读取超时 .build(); CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(config) .build(); ``` 3. **自动重定向** ```java HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()); ``` ### 注意事项 1. 使用 `try-with-resources` 确保自动关闭连接 2. 生产环境需添加异常处理(IOException等) 3. 释放资源:调用 `EntityUtils.consume(entity)` 防止内存泄漏 4. 设置用户代理:`httpGet.setHeader("User-Agent", "MyApp/1.0")`
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值