2016-11-22 35 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>