安卓发送网络请求通常基于以下两种方式:
库名 | 特点 |
---|---|
OkHttp | 轻量级、支持同步/异步请求、自动管理连接池 |
Retrofit | 基于OkHttp,支持RESTful API、可生成强类型接口代码 |
Volley | 适合小数据量请求、内置缓存机制 |
HttpURLConnection | Android原生API,需手动管理线程和连接复用 |
以POST请求为例,完整数据包包含:
[请求行] + [请求头] + [空行] + [请求体]
部分 | |
---|---|
请求行 | POST /api/login HTTP/1.1 |
请求头 | Content-Type: application/json User-Agent: OkHttp/4.9.3 |
空行 | <空行> |
请求体 | {"username":"test","password":"123456"} |
TCP数据包由以下部分组成:
[源端口] + [目标端口] + [序列号] + [确认号] + [数据偏移] + [标志位] + [窗口] + [校验和] + [紧急指针] + [有效载荷]
字段 | 作用 |
---|---|
序列号 | 标识数据包中数据的位置,用于重组数据流 |
确认号 | 接收方期望收到的下一个字节序号 |
标志位 | SYN/ACK(连接建立)、FIN(连接关闭) |
窗口大小 | 流量控制,告知对方可接收的数据量 |
implementation 'com.squareup.okhttp3:okhttp:4.9.3'
// 创建OkHttpClient实例 OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .build(); // 构建请求体 MediaType JSON = MediaType.get("application/json; charset=utf-8"); String json = "{"username":"test","password":"123456"}"; RequestBody body = RequestBody.create(json, JSON); // 构建请求 Request request = new Request.Builder() .url("https://api.example.com/login") .post(body) .addHeader("User-Agent", "AndroidApp/1.0") .build(); // 发送异步请求 client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { // 处理失败 Log.e("Network", "Request failed: " + e.getMessage()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { // 处理成功响应 String responseBody = response.body().string(); Log.d("Network", "Response: " + responseBody); } else { // 处理非2xx响应 Log.e("Network", "Server Error: " + response.code()); } } });
adb shell tcpdump -i any -s 0 -w capture.pcap
capture.pcap
分析View > Tool Windows > Network Inspector
中启动监控问题 | 现象 | 解决方案 |
---|---|---|
SSL握手失败 | javax.net.ssl.SSLHandshakeException: Certificate not trusted | 使用自定义TrustManager 禁用证书验证(仅限测试环境) |
大文件上传失败 | java.net.ProtocolException: unexpected end of stream | 分片上传 设置 OkHttp 超时时间检查服务器接收逻辑 |
数据包丢失 | 请求超时或部分数据未到达服务器 | 启用TCP重传机制 检查网络环境 增加重试逻辑 |
A:
adb shell
命令抓包,过滤HTTP协议数据包。 adb shell tcpdump -i any -s 0 -w http_capture.pcap
A:
OkHttp
的ConnectionPool
减少TCP握手次数。 OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(chain -> { Response response = chain.proceed(chain.request()); return response.newBuilder() .header("Content-Encoding", "gzip") .build(); }) .build();
Cache-Control
头或OkHttp
缓存机制。