我有以下课程:
@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
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@378fd1ac
sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@378fd1ac
所以,即使我的contentType
是正确的,如何从JSON中检索我的数据?
答案 0 :(得分:1)
您应该从InputStream
JSONObject myData = new JSONObject(IOUtils.toString(connection.getInputStream(),
connection.getContentEncoding());
IOUtils
是Apache Commons IO实用程序库中的一个类。
答案 1 :(得分:0)
您可以在客户端应用程序中访问JSON对象。
为此你需要使用杰克逊Databind依赖:
<!-- 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>