衢州市火車站片區(qū)規(guī)劃直通車推廣計劃方案
目錄
- 一、POST 傳遞簡單的字符串內(nèi)容 .body(params)
- 二、POST 傳遞 Json 數(shù)據(jù),以表單類型傳遞 .form(params)
- 二、POST 傳遞 Json 數(shù)據(jù),以表單類型傳遞 .form(params) 和 .body(params) 方法效果等效的思路
- 四、傳統(tǒng)接口帶 token 驗證的代碼模板
- 參考鏈接
一、POST 傳遞簡單的字符串內(nèi)容 .body(params)
演示代碼
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import cn.hutool.http.HttpRequest;
/*** cf*/
public class TqOdpServiceClient {private static String url="url";;public static String execute(String http,String params) {JSONObject response = JSONObject.parseObject(HttpRequest.post(http + url).body(params).execute().body());return response;}
}
二、POST 傳遞 Json 數(shù)據(jù),以表單類型傳遞 .form(params)
演示代碼
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import cn.hutool.http.HttpRequest;
/*** cf*/
public class TqOdpServiceClient {private static String url="url";;public static String execute(String http) {HashMap<String, Object> params = new HashMap<>(2);params.put("test1", "測試數(shù)據(jù)");params.put("test2", "測試數(shù)據(jù)");JSONObject response = JSONObject.parseObject(HttpRequest.post(http + url).form(params).execute().body());return response;}
}
二、POST 傳遞 Json 數(shù)據(jù),以表單類型傳遞 .form(params) 和 .body(params) 方法效果等效的思路
演示代碼:可以看到 String newParams = JSON.toJSONString(params);
將 HashMap 類型的數(shù)據(jù)轉(zhuǎn)換為字符串類型,就可以作為字符串被傳遞到 body 內(nèi),后面就是對應(yīng)接口的后端數(shù)據(jù)處理問題了。
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import cn.hutool.http.HttpRequest;
/*** cf*/
public class TqOdpServiceClient {private static String url="url";;public static String execute(String http) {HashMap<String, Object> params = new HashMap<>(2);params.put("test1", "測試數(shù)據(jù)");params.put("test2", "測試數(shù)據(jù)");String newParams = JSON.toJSONString(params);JSONObject response = JSONObject.parseObject(HttpRequest.post(http + url).body(newParams).execute().body());return response;}
}
四、傳統(tǒng)接口帶 token 驗證的代碼模板
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;/*** cf*/
public class TqOdpServiceClient {private static String url="url";;public static String execute(String http, String accessToken) {JSONObject response = JSONObject.parseObject(HttpRequest.get(http + url).header(Header.AUTHORIZATION, "Bearer ".concat(accessToken)).execute().body());return response;}
}
參考鏈接
java】hutool發(fā)送http請求,配置ssl忽略
SpringBoot 項目使用hutool 工具進行 http 接口調(diào)用的處理方法