当前位置:首页 > 行业动态 > 正文

安卓开发发送数据的代码

安卓开发发送数据的代码示例

GET请求发送数据

代码示例

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetRequestExample {
    public static void sendGetRequest(String targetUrl) {
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                // 创建URL对象
                URL url = new URL(targetUrl);
                // 打开连接
                connection = (HttpURLConnection) url.openConnection();
                // 设置请求方法为GET
                connection.setRequestMethod("GET");
                // 设置超时时间
                connection.setConnectTimeout(5000);
                connection.setReadTimeout(5000);
                // 获取响应码
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    // 读取响应数据
                    InputStream inputStream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                    String line;
                    StringBuilder response = new StringBuilder();
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    // 在主线程更新UI(需通过Handler)
                    // handler.sendMessage(...);
                    System.out.println("Response: " + response.toString());
                } else {
                    System.out.println("GET request failed: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();
    }
}

关键点说明
| 步骤 | 说明 |
|———————|———————————————————————-|
| 创建URL对象 | new URL(targetUrl) |
| 打开连接 | url.openConnection() |
| 设置请求方法 | setRequestMethod("GET") |
| 处理响应码 | getResponseCode() 判断是否为 HTTP_OK |
| 读取输入流 | 使用 BufferedReader 逐行读取响应数据 |
| 异常处理与资源释放 | try-catch 捕获异常,finally 关闭连接 |


POST请求发送数据

代码示例

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.nio.charset.StandardCharsets;
public class PostRequestExample {
    public static void sendPostRequest(String targetUrl, String jsonData) {
        new Thread(() -> {
            HttpURLConnection connection = null;
            try {
                // 创建URL对象
                URL url = new URL(targetUrl);
                // 打开连接
                connection = (HttpURLConnection) url.openConnection();
                // 设置请求方法为POST
                connection.setRequestMethod("POST");
                // 设置请求头
                connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                // 允许输出数据
                connection.setDoOutput(true);
                // 写入请求体数据
                try (OutputStream outputStream = connection.getOutputStream()) {
                    byte[] data = jsonData.getBytes(StandardCharsets.UTF_8);
                    outputStream.write(data);
                    outputStream.flush();
                }
                // 获取响应码
                int responseCode = connection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    System.out.println("POST request success");
                } else {
                    System.out.println("POST request failed: " + responseCode);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }).start();
    }
}

关键点说明
| 步骤 | 说明 |
|———————|———————————————————————-|
| 设置请求头 | setRequestProperty("Content-Type", "application/json; charset=UTF-8") |
| 允许输出数据 | setDoOutput(true) |
| 写入请求体 | 通过 OutputStream 写入JSON数据 |
| 字符编码 | 使用 UTF-8 避免中文乱码 |

安卓开发发送数据的代码  第1张


异步处理网络请求

代码示例

import android.os.Handler;
import android.os.Looper;
public class NetworkUtils {
    private static final Handler handler = new Handler(Looper.getMainLooper());
    public static void runOnMainThread(Runnable runnable) {
        handler.post(runnable);
    }
}

调用示例

// 在子线程中执行网络请求后更新UI
NetworkUtils.runOnMainThread(() -> {
    // 更新UI操作,例如显示Toast或修改TextView
});

关键点说明
| 工具 | 作用 |
|——————–|———————————————————————-|
| Handler | 将任务切换到主线程执行 |
| Looper.getMainLooper() | 获取主线程的Looper对象 |


权限配置

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

相关问题与解答

问题1:如何解析服务器返回的JSON数据?

解答
可以使用 Gsonorg.json 库解析JSON数据。

import com.google.gson.Gson;
// 假设服务器返回的JSON为:{"name":"张三","age":25}
String jsonResponse = "{"name":"张三","age":25}";
Gson gson = new Gson();
Person person = gson.fromJson(jsonResponse, Person.class);
// Person类需定义对应字段和getter/setter

问题2:如何处理网络请求中的异常?

解答

  1. 捕获异常:在 try-catch 中处理 IOExceptionMalformedURLException 等。
  2. 超时设置:通过 setConnectTimeoutsetReadTimeout 避免长时间等待。
  3. 错误码处理:根据 getResponseCode() 判断非200状态码(如404、500)。
  4. 日志记录:使用 Log.e 打印错误日志,便于调试。

示例

} catch (IOException e) {
    Log.e("NetworkError", "IO异常: " + e.getMessage());
} catch (Exception e) {
    Log.e("NetworkError", "未知错误: " + e.getMessage());
}
0