springbootRestTemplate发送get请求的踩坑及解决spring boot RestTemplate 发送get请求踩坑
闲话少说,代码说话
RestTemplate 实例
⼿动实例化,这个我基本不⽤
RestTemplate restTemplate = new RestTemplate();
依赖注⼊,通常情况下我使⽤ java 包下的类构建的 SimpleClientHttpRequestFactory
@Configuration
public class RestConfiguration {
@Bean
@ConditionalOnMissingBean({RestOperations.class, RestTemplate.class})
public RestOperations restOperations() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setReadTimeout(5000);
requestFactory.setConnectTimeout(5000);
RestTemplate restTemplate = new RestTemplate(requestFactory);
// 使⽤ utf-8 编码集的 conver 替换默认的 conver(默认的 string conver 的编码集为 "ISO-8859-1")
List<HttpMessageConverter<?>> messageConverters = MessageConverters();
Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
while (iterator.hasNext()) {
HttpMessageConverter<?> converter = ();
if (converter instanceof StringHttpMessageConverter) {
}
}
messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
}
请求地址
get 请求 url 为
localhost:8080/test/sendSms?phone=⼿机号&msg=短信内容
错误使⽤
@Autowired
private RestOperations restOperations;
public void test() throws Exception{
String url = "localhost:8080/test/sendSms";
Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("phone", "151xxxxxxxx");
uriVariables.put("msg", "测试短信内容");
String result = ForObject(url, String.class, uriVariables);
}spring boot原理 通俗面试
服务器接收的时候你会发现,接收的该请求时没有参数的
正确使⽤
@Autowired
private RestOperations restOperations;
public void test() throws Exception{
String url = "localhost:8080/test/sendSms?phone={phone}&msg={phone}";
Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("phone", "151xxxxxxxx");
uriVariables.put("msg", "测试短信内容");
String result = ForObject(url, String.class, uriVariables);
}
等价于
@Autowired
private RestOperations restOperations;
public void test() throws Exception{
String url = "localhost:8080/test/sendSms?phone={phone}&msg={phone}";
String result = ForObject(url, String.class,  "151xxxxxxxx", "测试短信内容");
}
springboot restTemplate访问get,post请求的各种⽅式
springboot中封装好了访问外部请求的⽅法类,那就是RestTemplate。下⾯就简单介绍⼀下,RestTemplate访问外部请求的⽅法。
get请求
⾸先get请求的参数是拼接在url后⾯的。所以不需要额外添加参数。但是也需要分两种情况。
1、有请求头
由于 getForEntity() 和 getForObject() 都⽆法加⼊请求头。所以需要请求头的连接只能使⽤ exchange() 来访问。代码如下
public JSONObject test(){
try {
RestTemplate re = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
String url = "test.api?id=123";
headers.set("Content-Type","application/json");
HttpEntity<JSONObject> jsonObject= re.exchange(url, HttpMethod.GET,new HttpEntity<>(headers),JSONObject.class);
log.info("返回:{}",Body());
Body();
}catch (Exception e){
<(e.getMessage());
}
return null;
}
2、⽆请求头
⽆需请求头的可以⽤三个⽅法实现。getForEntity() 和 getForObject() 还有 exchange() 都可以实现。下⾯讲前两种⽤的⽐较多的。
getForEntity()
public JSONObject test(){
try {
RestTemplate re = new RestTemplate();
String url = "api.help.bj/apis/alarm/?id=101020100";
HttpEntity<JSONObject> jsonObject= re.getForEntity(url,JSONObject.class);
log.info("返回:{}",Body());
Body();
}catch (Exception e){
<(e.getMessage());
}
return null;
}
getForObject()
public JSONObject test(){
try {
RestTemplate re = new RestTemplate();
String url = "api.help.bj/apis/alarm/?id=101020100";
JSONObject jsonObject= re.getForObject(url,JSONObject.class);
log.info("返回:{}",jsonObject);
return jsonObject;
}catch (Exception e){
<(e.getMessage());
}
return null;
}
post请求
post请求也分⼏种情况
1、参数在body的form-data⾥⾯
public static JSONObject test(){
try {
RestTemplate re = new RestTemplate();
String url = "localhost:8101/test";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> loginJson = new LinkedMultiValueMap<>();
loginJson.add("id", "123");
JSONObject jsonObject= re.postForObject(url,new HttpEntity<>(loginJson,headers),JSONObject.class);            log.info("返回:{}",jsonObject);
return jsonObject;
}catch (Exception e){
<(e.getMessage());
}
return null;
}
还可以把 postForObject 换成 postForEntity
2、参数在body的x-www-from-urlencodeed⾥⾯
只需要把请求头的setContentType改成下⾯即可
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
public static JSONObject test(){
try {
RestTemplate re = new RestTemplate();
String url = "localhost:8101/test";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, Object> loginJson = new LinkedMultiValueMap<>();
loginJson.add("id", "123");
JSONObject jsonObject= re.postForObject(url,new HttpEntity<>(loginJson,headers),JSONObject.class);            log.info("返回:{}",jsonObject);
return jsonObject;
}catch (Exception e){
<(e.getMessage());
}
return null;
}
3、参数在body的raw⾥⾯
public static JSONObject test(){
try {
RestTemplate re = new RestTemplate();
String url = "localhost:8101/test";
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type","application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("id","1");
JSONObject jsonObject1 = restTemplate
.postForObject(url,new HttpEntity<>(jsonObject,headers),JSONObject.class);            log.info("返回:{}",jsonObject1);
return jsonObject;
}catch (Exception e){
<(e.getMessage());
}
return null;
}
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。