使用restTemplate.postForEntity()的问题
作者:海枯石烂i
这篇文章主要介绍了使用restTemplate.postForEntity()的问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
使用restTemplate.postForEntity()
@Component
public class RemoteQuestUtil {
@Autowired
private RestTemplate restTemplate;
public String send(String srvcCode, String request){
//srvcCode 获取对应交易 现场适配
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的参数
RestTemplate().postForEntity() 是 Spring Framework 提供的一个用于发送 HTTP POST 请求并获取响应的方法。
以下是该方法的参数详解
url(String 类型):请求的目标 URL。可以是一个字符串形式的 URL,也可以是一个 URI 对象。示例:“http://example.com/api”。request(Object 类型):表示要发送的请求体内容。可以是一个简单对象、一个 HttpEntity 对象或一个 MultiValueMap(用于传递表单数据)。根据实际需要确定所需的请求体内容。responseType(Class 类型):表示期望的响应类型。可以是任何 Java 类型,包括自定义类型。例如,如果期望返回一个 User 对象,则可以将其设置为 User.class。uriVariables(Object… 类型):可选参数,用于填充 URL 中的占位符。如果 URL 中包含占位符,可以通过这个参数来提供具体的值。uri(URI 类型):可选参数,代替 url 参数,用于指定完整的请求目标 URI。
注意事项
- 如果使用 url 参数,uriVariables 参数将用于替换 URL 中的占位符。
- 如果使用 uri 参数,则忽略 url 和 uriVariables 参数。
- 如果请求需要设置请求头或其他配置信息,可以使用 HttpEntity 对象构建请求。
方法返回一个 ResponseEntity 对象,其中包含 HTTP 响应的状态码、响应头以及解析后的响应体。你可以通过 ResponseEntity 对象获取所需的数据。
以下是一个使用 RestTemplate().postForEntity() 方法发送 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);
// 发送 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数据,
例如:
Map<String, Object> requestMap = new HashMap<>();
// 发动机型号
requestMap.put("engine_model", "1234");
// 发动机编号
requestMap.put("engine_code", "6789");
// 请求 URL
String url = "http://example.com/api";
// 调对方接口
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");根据上述的布尔值判断接口是否调用成功,进行后续逻辑。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
