java開發(fā)hutool HttpUtil網絡請求工具使用demo
更新時間:2023年07月09日 14:31:00 作者:AC編程
這篇文章主要為大家介紹了hutool之HttpUtil網絡請求工具使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
一、測試代碼
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class Test {
public static void main(String[] args) {
requestToken();
}
public static String requestToken() {
try {
String url = "https://alanchen.com/auth/getToken/V2";
HttpRequest request = HttpUtil.createPost(url);
request.header("PartnerCode", "testCode");
Map<String, String> param = new HashMap();
param.put("partnerCode", "testCode");
param.put("partnerSecret", "secret");
Gson gson = new Gson();
String body = gson.toJson(param);
request.body(body);
HttpResponse execute = request.execute();
if (!execute.isOk()) {
log.error("請求token失敗,body={},execute={}", execute.body(), execute);
throw new RuntimeException(execute.body());
}
String res = UnicodeUtil.toString(execute.body());
JSONObject jsonObject = JSONUtil.parseObj(res, true);
AuthTokenResResult resultObj = jsonObject.toBean(AuthTokenResResult.class, true);
log.info("requestToken,resultObj={}", resultObj);
if (resultObj.getCode() != 200) {
log.error("獲取token失敗,code={},msg={},result={}", resultObj.getCode(), resultObj.getMsg(), resultObj);
throw new RuntimeException("獲取token失敗,code=" + resultObj.getCode() + ",msg=" + resultObj.getMsg());
}
if (resultObj.getData() == null) {
log.error("獲取token為空,code={},msg={},result={}", resultObj.getCode(), resultObj.getMsg(), resultObj);
throw new RuntimeException("獲取token為空,code=" + resultObj.getCode() + ",msg=" + resultObj.getMsg());
}
return resultObj.getData().getToken();
} catch (Exception e) {
log.error("requestToken失敗,msg={}", e.getMessage());
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
@Data
public class AuthTokenResResult {
private int code;
private String msg;
private AuthToken data;
private long count;
}
@Data
public class AuthToken {
private String token;
private long expireAt;
}
}二、代碼片段
// 設置請求體參數
String requestBody = "{\"param1\": \"value1\", \"param2\": \"value2\"}";
httpRequest.body(requestBody)
.setHeader("Content-Type", "application/json")
.timeout(20000); // 設置超時時間為20秒
// 設置請求參數
httpRequest.setQueryParam("param1", "value1")
.setHeader("User-Agent", "Hutool")
.timeout(20000); // 設置超時時間為20秒以上就是java開發(fā)hutool HttpUtil網絡請求工具使用demo的詳細內容,更多關于hutool HttpUtil網絡請求的資料請關注腳本之家其它相關文章!
相關文章
SpringBoot3.0+SpringSecurity6.0+JWT的實現
本文主要介紹了SpringBoot3.0+SpringSecurity6.0+JWT的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-11-11

