Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header

Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header

{
“Author”: “tomcat and jerry”,
“url”:“http://www.cnblogs.com/tomcatandjerry/p/5899722.html
}
Spring RestTemplate, 使用java访问URL更加优雅,更加方便。

核心代码:

String url = “http://localhost:8080/json”;
JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
就这么简单,API访问完成了!

附上SpringBoot相关的完整代码:

RestTemplateConfig.java

@Configuration
public class RestTemplateConfig{
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}

@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
    SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
    factory.setReadTimeout(5000);//ms
    factory.setConnectTimeout(15000);//ms
    return factory;
}

}

SpringRestTemplateApp.java
@RestController
@EnableAutoConfiguration
@Import(value = {Conf.class})
public class SpringRestTemplateApp {

@Autowired
RestTemplate restTemplate;

/***********HTTP GET method*************/
@RequestMapping("")
public String hello(){
    String url = "http://localhost:8080/json";
    JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
    return json.toJSONString();
}

@RequestMapping("/json")
public Object genJson(){
    JSONObject json = new JSONObject();
    json.put("descp", "this is spring rest template sample");
    return json;
}

/**********HTTP POST method**************/
@RequestMapping("/postApi")
public Object iAmPostApi(@RequestBody JSONObject parm){
    System.out.println(parm.toJSONString());
    parm.put("result", "hello post");
    return parm;
}

@RequestMapping("/post")
public Object testPost(){
    String url = "http://localhost:8080/postApi";
    JSONObject postData = new JSONObject();
    postData.put("descp", "request for post");
    JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
    return json.toJSONString();
}

public static void main(String[] args) throws Exception {
    SpringApplication.run(SpringRestTemplateApp.class, args);
}

}
另外还支持异步调用AsyncRestTemplate
复制代码
@RequestMapping("/async")
public String asyncReq(){
String url = “http://localhost:8080/jsonAsync”;
ListenableFuture<ResponseEntity> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
future.addCallback(new SuccessCallback<ResponseEntity>() {
public void onSuccess(ResponseEntity result) {
System.out.println(result.getBody().toJSONString());
}
}, new FailureCallback() {
public void onFailure(Throwable ex) {
System.out.println(“onFailure:”+ex);
}
});
return “this is async sample”;
}

===============================

贴一段post请求如何自定义header

@RequestMapping("/headerApi")//模拟远程的restful API
public JSONObject withHeader(@RequestBody JSONObject parm, HttpServletRequest req){
System.out.println(“headerApi=====”+parm.toJSONString());
Enumeration headers = req.getHeaderNames();
JSONObject result = new JSONObject();
while(headers.hasMoreElements()){
String name = headers.nextElement();
System.out.println("["+name+"]="+req.getHeader(name));
result.put(name, req.getHeader(name));
}
result.put(“descp”, “this is from header”);
return result;
}
@RequestMapping("/header")
public Object postWithHeader(){
    //该方法通过restTemplate请求远程restfulAPI
HttpHeaders headers = new HttpHeaders();
headers.set(“auth_token”, “asdfgh”);
headers.set(“Other-Header”, “othervalue”);
headers.setContentType(MediaType.APPLICATION_JSON);
JSONObject parm = new JSONObject();
parm.put(“parm”, “1234”);
HttpEntity entity = new HttpEntity(parm, headers);
HttpEntity response = restTemplate.exchange(
http://localhost:8080/headerApi”, HttpMethod.POST, entity, String.class);//这里放JSONObject, String 都可以。因为JSONObject返回的时候其实也就是string
return response.getBody();
}

原网址:https://www.cnblogs.com/tomcatandjerry/p/5899722.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值