用于发起表单提交调用第三方RestApi
public static void main(String[] args) {
String url="https://sms.yunpian.com/v2/sms/single_send.json";
String apikey="f0cfcdasdfd52as2df1021ec1d81";
String mobeil = "+8613361261493";
String text = "【Sakura】您本次操作的验证码为[548973]请妥善保管,不要向任何人提供验证码";
// 创建请求头写入媒体类型为表单
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 创建表单请求参数
LinkedMultiValueMap<String, String> valueMap = new LinkedMultiValueMap<>();
valueMap.add("apikey",apikey);
valueMap.add("mobile",mobeil);
valueMap.add("text",text);
// 组装请求体,泛型为上面的表单map
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(valueMap, headers);
// 发起请求并打印结果,以String接收响应结果
String responseJson = new RestTemplate().postForObject(url, request, String.class);
System.out.println(responseJson);
}
发送Json时
public static void main(String[] args) {
String url ="https://api.paystack.co/transaction/initialize";
String authorization="Bearer sk_test_761132c0c3bf7b66c0087";
PayStackInitTransactionDto initDto = PayStackInitTransactionDto.builder()
.amount("11233")
.currency(CurrencyEnum.ZAR.getCurrency())
.email("10000@qq.cc")
.metadata(new HashMap<String, Object>() {{
put("orderId","asda");
}})
.build();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(JSONObject.toJSONString(initDto), headers);
JSONObject jsonObject = new RestTemplate().postForObject(url, request, JSONObject.class);
System.out.println(jsonObject);
}