最簡單的 GET 請求:
String result = HttpUtil.get("https://www.baidu.com");
帶參數的 GET 請求:
// 方法1: 直接拼接URL參數
String result = HttpUtil.get("https://www.baidu.com?name=張三&age=18");// 方法2: 使用 HashMap 構建參數
HashMap<String, Object> params = new HashMap<>();
params.put("name", "張三");
params.put("age", "18");
String result = HttpUtil.get("https://www.baidu.com", params);
POST 請求:
// 簡單POST
String result = HttpUtil.post("https://www.baidu.com", "body content");// 帶表單參數的POST
HashMap<String, Object> params = new HashMap<>();
params.put("name", "張三");
params.put("age", "18");
String result = HttpUtil.post("https://www.baidu.com", params);
發送 JSON:
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("name", "張三");
paramMap.put("age", 18);String result = HttpRequest.post("https://www.baidu.com").header("Content-Type", "application/json").body(JSONUtil.toJsonStr(paramMap)).execute().body();
高度自定義的請求:
HttpRequest request = HttpRequest.post("https://www.baidu.com").header("Authorization", "Bearer token123").header("Custom-Header", "value").timeout(20000) //超時時間20秒.form(params) //表單參數.cookie("sessionId", "abc123");HttpResponse response = request.execute();
String result = response.body();
int status = response.getStatus();
文件上傳:
HashMap<String, Object> params = new HashMap<>();
params.put("file", FileUtil.file("path/file.jpg"));
String result = HttpUtil.post("https://www.baidu.com/upload", params);
處理響應:
HttpResponse response = HttpRequest.get("https://www.baidu.com").execute();
// 獲取響應狀態碼
int status = response.getStatus();
// 獲取響應頭
String contentType = response.header("Content-Type");
// 獲取響應體
String body = response.body();
// 獲取Cookies
List<HttpCookie> cookies = response.getCookies();
設置代理:
HttpRequest.get("https://www.baidu.com").setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888))).execute();
請求建議:
- 建議在生產環境中設置合適的超時時間
- 對于大量請求,使用 HttpUtil.createGet() 或 HttpUtil.createPost() 預創建請求對象
- 處理響應時注意異常處理
- 如果需要復用連接,考慮使用 HttpUtil.createHttp() 創建客戶端
錯誤處理示例:
try {HttpResponse response = HttpRequest.get("https://www.baidu.com").timeout(20000).execute();if (response.isOk()) {String result = response.body();// 處理正常響應}
} catch (HttpException e) {// 處理超時等網絡異常e.printStackTrace();
} catch (Exception e) {// 處理其他異常e.printStackTrace();
}