Spring mvc restful service and client

时间:2014-06-03 09:05:53

标签: java json spring rest

嗨朋友,这是服务器端的服务代码,

 @RequestMapping(value = "/pack/{id}", method = RequestMethod.GET, headers="Accept=application/json", produces = "application/json")
 public @ResponseBody String getPackByID(@PathVariable("id") int packageID) {

        System.out.println("In RESTful Service menthod ****************************");
        Vspackages vspackages = Vspackages.findVspackages(Integer.valueOf(packageID));
        return vspackages.customToJson();
 }

它的工作,当URI调用(http://thevenueplanner.com/pack/480

时返回json对象

我编写Java客户端以从URI

访问返回JSON对象

客户端代码

字符串BASE_URI =“http://thevenueplanner.com/”;

public void givenConsumingJson_whenReadingTheFoo_thenCorrect() {
    String URI = BASE_URI + "pack/{id}";

    JSONArray arr = null;

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.setMessageConverters(getMessageConverters());

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<String> entity = new HttpEntity<String>(headers);             

    ResponseEntity<JSONObject> response = restTemplate.exchange(URI, HttpMethod.GET, entity, JSONObject.class, "480");                


    JSONObject resource = restTemplate.getForObject(URI, JSONObject.class, "480");

    System.out.println("Response: "+response.toString());

    System.out.println("resource: "+resource.toString());

}
private List<HttpMessageConverter<?>> getMessageConverters() {


     ObjectMapper mapper = new ObjectMapper();                               

     mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


     MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
     messageConverter.setObjectMapper(mapper);               

    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    converters.add(messageConverter);
    return converters;

}

成功讯息是:

  

响应:&lt; 200 OK,{},{Server = [Apache-Coyote / 1.1],Content-Type = [application / json; charset = UTF-8],Content-Length = [5189],Date = [星期二,2014年6月3日08:54:50 GMT]}&gt;   资源:{}

它不会给出JSON对象,但它会在成功消息中告诉它的内容长度,

如何从URI到客户端获取JSON对象

0 个答案:

没有答案