我有以下类:如何从我的方法检索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中检索我的数据?
这看起来像代码*送*有些JSON在休耕的事情一个POST请求(尽管它不起作用),不接收来自GET的JSON响应。 – OrangeDog
看起来你使用的是Spring的服务器,为什么不使用[Spring的客户端](http://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework /web/client/RestTemplate.html)? – OrangeDog