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<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
        future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() {
            public void onSuccess(ResponseEntity<JSONObject> 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<String> 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<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers); HttpEntity<String> response = restTemplate.exchange( "http://localhost:8080/headerApi", HttpMethod.POST, entity, String.class);//這里放JSONObject, String 都可以。因為JSONObject返回的時候其實也就是string return response.getBody(); }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM