使用restTemplate.postForEntity()的問題
使用restTemplate.postForEntity()
@Component
public class RemoteQuestUtil {
@Autowired
private RestTemplate restTemplate;
public String send(String srvcCode, String request){
//srvcCode 獲取對應交易 現(xiàn)場適配
MockPropertiesUtil instance = MockPropertiesUtil.getInstance();
String url = instance.getProperty(srvcCode);
//處理接收接口只支持JSONOBject
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity request1 = new HttpEntity<>(request, headers);
log.info("請求報文:{}",request);
ResponseEntity<String> jsonObjectResponseEntity = restTemplate.postForEntity(url, request1, String.class);
String resp = jsonObjectResponseEntity.getBody();
log.info("響應報文:{}",resp);
return resp;
}
}MockPropertiesUtil
public class MockPropertiesUtil {
public static Properties pro = new Properties();
public static MockPropertiesUtil instance = new MockPropertiesUtil();
public static MockPropertiesUtil getInstance() {
return instance;
}
static {
InputStream in ;
try {
in = MockPropertiesUtil.class.getClassLoader().getResourceAsStream("mock-properties.properties"); //加載文件將文件加載為
pro = new Properties();
pro.load(in);
} catch (IOException e) {
log.error("加載Mock配置文件[mock-properties.properties]時異常",e);
throw new PlatformException(PlatformError.LOADCONFIG_ERROR);
}
try {
if (in != null){
in.close();
}
} catch (IOException e) {
log.error("關閉流異常",e);
}
}
public String getProperty(String key) {
if (StringUtil.isEmpty(key)) {
log.warn("key is null.");
return null;
}
if (!pro.containsKey(key)){
log.info("無此服務碼:{}",key);
throw new PlatformException(PlatformError.GET_URL_BY_CODE_ERROR);
}
//通過鍵值獲得對應的url key=url
String url = pro.getProperty(key);
log.info("服務碼:{},對應的url為:{}",key,url);
return url;
}
}RestTemplate().postForEntity的參數(shù)
RestTemplate().postForEntity() 是 Spring Framework 提供的一個用于發(fā)送 HTTP POST 請求并獲取響應的方法。
以下是該方法的參數(shù)詳解
url(String 類型):請求的目標 URL??梢允且粋€字符串形式的 URL,也可以是一個 URI 對象。示例:“http://example.com/api”。request(Object 類型):表示要發(fā)送的請求體內(nèi)容??梢允且粋€簡單對象、一個 HttpEntity 對象或一個 MultiValueMap(用于傳遞表單數(shù)據(jù))。根據(jù)實際需要確定所需的請求體內(nèi)容。responseType(Class 類型):表示期望的響應類型??梢允侨魏?Java 類型,包括自定義類型。例如,如果期望返回一個 User 對象,則可以將其設置為 User.class。uriVariables(Object… 類型):可選參數(shù),用于填充 URL 中的占位符。如果 URL 中包含占位符,可以通過這個參數(shù)來提供具體的值。uri(URI 類型):可選參數(shù),代替 url 參數(shù),用于指定完整的請求目標 URI。
注意事項
- 如果使用 url 參數(shù),uriVariables 參數(shù)將用于替換 URL 中的占位符。
- 如果使用 uri 參數(shù),則忽略 url 和 uriVariables 參數(shù)。
- 如果請求需要設置請求頭或其他配置信息,可以使用 HttpEntity 對象構建請求。
方法返回一個 ResponseEntity 對象,其中包含 HTTP 響應的狀態(tài)碼、響應頭以及解析后的響應體。你可以通過 ResponseEntity 對象獲取所需的數(shù)據(jù)。
以下是一個使用 RestTemplate().postForEntity() 方法發(fā)送 POST 請求的示例代碼:
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
// 請求 URL
String url = "http://example.com/api";
// 構建請求體
User user = new User("John", 30); // 自定義 User 類
HttpEntity<User> request = new HttpEntity<>(user);
// 發(fā)送 POST 請求并獲取響應
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
// 獲取響應結果
HttpStatus statusCode = response.getStatusCode();
HttpHeaders headers = response.getHeaders();
String body = response.getBody();
// 處理響應結果
System.out.println("Status Code: " + statusCode);
System.out.println("Response Headers: " + headers);
System.out.println("Response Body: " + body);
}
}也可以使用Map傳遞Json數(shù)據(jù),
例如:
Map<String, Object> requestMap = new HashMap<>();
// 發(fā)動機型號
requestMap.put("engine_model", "1234");
// 發(fā)動機編號
requestMap.put("engine_code", "6789");
// 請求 URL
String url = "http://example.com/api";
// 調(diào)對方接口
ResponseEntity<String> responseEntity = new RestTemplate().postForEntity(url, requestMap , String.class);
Map<String, Object> responseBodyMap = GsonUtil.gsonToMaps(responseEntity.getBody());
// 對方接口返回值 true傳輸成功 false 失敗
Map<String, Object> result = (Map<String, Object>) responseBodyMap.get("result");
boolean isSuccess = (Boolean) result.get("success");根據(jù)上述的布爾值判斷接口是否調(diào)用成功,進行后續(xù)邏輯。
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring框架基于AOP實現(xiàn)簡單日志管理步驟解析
這篇文章主要介紹了Spring框架基于AOP實現(xiàn)簡單日志管理步驟解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-06-06
IntelliJ IDEA Tomcat控制臺中文亂碼問題的四種解決方案
這篇文章主要給大家分享了4種方法完美解決IntelliJ IDEA Tomcat控制臺中文亂碼問題,文中有詳細的圖文介紹,對我們的學習或工作有一定的幫助,需要的朋友可以參考下2023-08-08
Springboot集成Minio實現(xiàn)文件上傳基本步驟
這篇文章主要介紹了Springboot集成Minio實現(xiàn)文件上傳基本步驟,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2025-06-06
一步步教你整合SSM框架(Spring MVC+Spring+MyBatis)詳細教程
使用SSM(Spring、SpringMVC和Mybatis)已經(jīng)有段時間了,項目在技術上已經(jīng)沒有什么難點了,基于現(xiàn)有的技術就可以實現(xiàn)想要的功能,下面這篇文章主要給大家介紹了關于整合SSM框架:Spring MVC + Spring + MyBatis的相關資料,需要的朋友可以參考下。2017-07-07

