2016-11-22 49 views
-1

我有以下类:如何从我的方法检索JSON?

@Path("/") 
public class RESTService { 

@GET 
@Path("verifica") 
@Produces(MediaType.TEXT_PLAIN) 
public Response verificaREST(InputStream dadoRecebido) { 
    String resultado = "Servico REST startou sucesso"; 
    return Response.status(200).entity(resultado).build(); 
} 

@Path("multiplica:{n}") 
@GET 
@Produces(MediaType.APPLICATION_JSON) 
public Response TimesTwo(@PathParam("n") float n) throws JSONException { 

    JSONObject jsonObject = new JSONObject(); 
    jsonObject.put("primeiro", n); 
    jsonObject.put("segundo", 2 * n); 
    return Response.status(200).entity(jsonObject.toString()).build(); 
} 

}

当我接取http://localhost:8080/RestWithJSON/123/verificawith这个我可以看到Servico REST startou sucesso。当我输入http://localhost:8080/RestWithJSON/123/multiplica:4时,我可以在我的浏览器上看到{"primeiro":4,"segundo":8}。现在,我尝试使用下面的客户端类从TimesTwo方法得到一些JSON:

URL url = new URL("http://localhost:8080/RestWithJSON/123/multiplica:24"); 
    URLConnection connection = url.openConnection(); 
    connection.setDoOutput(true); 
    connection.setRequestProperty("Content-Type", "application/json"); 
    connection.setConnectTimeout(5000); 
    connection.setReadTimeout(5000); 
    System.out.println(connection.getContentType()); 
    System.out.println(connection.getInputStream().toString()); 
    System.out.println(connection.getContent()); 

但是有了这个,我只得到了以下几点:

application/json 
[email protected]d1ac 
[email protected]d1ac 

所以,即使我的contentType是正确的,我如何从JSON中检索我的数据?

+0

这看起来像代码*送*有些JSON在休耕的事情一个POST请求(尽管它不起作用),不接收来自GET的JSON响应。 – OrangeDog

+1

看起来你使用的是Spring的服务器,为什么不使用[Spring的客户端](http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework /web/client/RestTemplate.html)? – OrangeDog

回答

1

你应该InputStream

JSONObject myData = new JSONObject(IOUtils.toString(connection.getInputStream(), 
    connection.getContentEncoding()); 

IOUtils是从Apache下议院IO工具库的类。

0

您可以访问客户端应用程序中的JSON对象。

对于您需要使用休耕杰克逊数据绑定依赖性:

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> 
     <dependency> 
      <groupId>com.fasterxml.jackson.core</groupId> 
      <artifactId>jackson-databind</artifactId> 
      <version>2.1.4</version> 
     </dependency> 

而且你需要配置在applicationContext.xml文件

<beans:bean -- 

<!-- To convert JSON to Object and vice versa --> 
    <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 
    </beans:bean> 

</beans:bean>