OkHttp 是 Square 開源的高性能 HTTP 客戶端,原生支援 HTTP/2、連接池、GZIP、響應緩存,是 Android 與 Java 後端調用第三方 API、微服務互調的首選。本文以 Spring MVC 為服務端示例,演示 OkHttp 同步發送 GET/POST 請求的完整流程。
<dependency>
<groupId>com.squareup.okhttp</groupId>
<artifactId>okhttp</artifactId>
<version>2.7.5</version>
</dependency>
// implementation 'com.squareup.okhttp:okhttp:2.7.5'
OkHttp 3.x+ 包名變更為
com.squareup.okhttp3,API 微調,遷移參考官方遷移指南。
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired UserService userService;
@Autowired Gson gson;
@GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
public String list(@RequestParam int pageNo, @RequestParam int pageSize) {
Map<String, Object> result = new HashMap<>();
try {
List<User> users = userService.queryPage(pageNo, pageSize);
result.put("userList", users);
return gson.toJson(result);
} catch (Exception e) {
log.error("查詢失敗", e);
return gson.toJson(Result.fail());
}
}
}
public class OkHttpGetDemo {
private static final OkHttpClient client = new OkHttpClient(); // 單例複用
public static void main(String[] args) throws IOException {
String url = "https://localhost:8080/user/list?pageNo=0&pageSize=10";
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("HTTP " + response.code());
String body = response.body().string();
System.out.println(body);
}
}
}
public class OkHttpPostDemo {
private static final OkHttpClient client = new OkHttpClient();
private static final MediaType FORM = MediaType.parse("application/x-www-form-urlencoded");
public static void main(String[] args) throws IOException {
String url = "https://localhost:8080/user/list"; // 假設 POST 同樣接口
RequestBody formBody = new FormBody.Builder()
.add("pageNo", "0")
.add("pageSize", "10")
.build();
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
}
}
}
{
"userList": [
{"id":49,"name":"876","address":"876"},
{"id":50,"name":"antd","address":"antd"},
...
{"id":58,"name":"613ee3a3-fb87-4413-a8e0-9272d10ad4a7","address":"6427"}
]
}
| 場景 | 關鍵 API | 備註 |
|---|---|---|
| JSON 請求體 | RequestBody.create(JSON, jsonString) | 配合 Gson/Jackson 序列化 |
| 文件上傳 | MultipartBody.Builder.addFormDataPart() | 大文件建議流式 |
| 超時控制 | client.newBuilder().connectTimeout(10, TimeUnit.SECONDS) | 連接/讀寫/調用三種超時 |
| 攔截器/日誌 | addInterceptor(new HttpLoggingInterceptor().setLevel(BASIC)) | 調試神器 |
| 異步回調 | client.newCall(req).enqueue(new Callback() {...}) | 非阻塞,UI 線程友好 |
| 連接池調優 | new ConnectionPool(5, 5, TimeUnit.MINUTES) | 最大閒置連接/存活時間 |
try-with-resources 或手動 response.close(),否則連接無法回收。IOException)、HTTP 錯誤碼、業務邏輯錯誤,分別重試/告警/降級。遷移建議:新項目直接使用
okhttp3(最新 4.12.x),包名okhttp3,API 更現代化,支援 Kotlin 協程、WebSocket、DNS 緩存等新特性。