Android使用URLConnection发送GET/POST请求详解

0 下载量 52 浏览量 更新于2024-09-05 收藏 197KB PDF 举报
"Android使用URLConnection提交HTTP请求的实现方法及示例代码" 在Android开发中,与服务器进行数据交互是常见的需求, HttpURLConnection是Java提供的一个标准库,用于处理HTTP协议的请求和响应。本篇文章主要讲解如何在Android应用中利用URLConnection实现HTTP请求,包括GET和POST两种方式。 首先,我们需要理解URLConnection的工作流程。当调用URL对象的`openConnection()`方法时,系统会返回一个URLConnection实例,这个实例是与目标URL建立连接的基础。接下来,可以通过设置URLConnection的属性和请求头来定制请求行为。对于GET请求,只需要调用`connect()`方法即可完成请求。而对于POST请求,需要先写入请求参数到输出流,然后调用`connect()`方法。 以下是一个简单的GET请求的实现步骤: 1. 创建URL对象,指定请求的URL地址。 2. 调用URL对象的`openConnection()`方法获取URLConnection对象。 3. 设置URLConnection的一些属性,如超时时间。 4. 调用`connect()`方法建立连接。 5. 通过`getInputStream()`获取输入流,读取服务器返回的数据。 对于POST请求,还需额外的步骤: 1. 获取URLConnection的输出流`getOutputStream()`。 2. 将POST参数写入输出流。 3. 关闭输出流。 4. 再次调用`connect()`方法建立连接,因为POST请求需要在写入参数后才建立连接。 5. 同样通过`getInputStream()`读取响应数据。 以下是一个名为`GetPostUtil`的工具类示例,包含了GET和POST请求的实现: ```java package com.fukaimei.getposttest; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public class GetPostUtil { private static final String TAG = "GetPostUtil"; / * 向指定URL发送GET方式的请求 * * @param url 发送请求的URL * @return 服务器返回的字符串 */ public static String sendGet(String url) { URLConnection connection = null; BufferedReader reader = null; try { URL urlObj = new URL(url); connection = urlObj.openConnection(); // 设置超时 connection.setConnectTimeout(5000); connection.setReadTimeout(5000); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } return response.toString(); } catch (IOException e) { Log.e(TAG, "发送GET请求失败:" + e.getMessage()); return null; } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } / * 向指定URL发送POST方式的请求 * * @param url 发送请求的URL * @param params 请求参数,key-value形式的列表 * @return 服务器返回的字符串 */ public static String sendPost(String url, List<Param> params) { URLConnection connection = null; PrintWriter writer = null; BufferedReader reader = null; try { URL urlObj = new URL(url); connection = urlObj.openConnection(); connection.setDoOutput(true); // 允许输出 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置请求类型 writer = new PrintWriter(connection.getOutputStream()); for (Param param : params) { writer.print(param.getKey() + "=" + param.getValue() + "&"); } writer.flush(); // 刷新缓冲区,确保所有数据都已写出 writer.close(); // 开始接收响应 connection.connect(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } return response.toString(); } catch (IOException e) { Log.e(TAG, "发送POST请求失败:" + e.getMessage()); return null; } finally { if (writer != null) { writer.close(); } if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } public static class Param { private String key; private String value; public Param(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() { return value; } } } ``` 在这个工具类中,`sendGet`方法实现了GET请求,而`sendPost`方法实现了POST请求。POST请求中,我们使用`Param`类封装了请求参数,并在写入输出流时将这些参数按照URL编码的格式拼接起来。 在实际项目中,可以根据需要对请求过程进行优化,例如添加错误处理、使用线程池进行异步请求、处理响应状态码等。同时,也可以考虑使用第三方网络库如Volley、Retrofit或OkHttp,它们提供了更高级别的抽象和更好的性能。不过,了解基本的URLConnection用法对于理解网络请求的底层原理和自定义网络库的构建是非常有帮助的。