如何在java中阅读客户端的restful响应帖子

时间:2015-02-23 12:09:58

标签: java web-services post restful-architecture

我已将响应返回给客户

return Response.status(200).entity("Data was succesfully loaded into database").build();

我必须在客户端上阅读此客户端代码

 URL url=new URL(urlString);
       // URLConnection connection=url.openConnection();
        //connection.setDoOutput(true);
        HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("POST");
        httpCon.setRequestProperty("Content-Type", 
                "application/json");

如何在客户端阅读这些类型的回复

1 个答案:

答案 0 :(得分:0)

一旦你有了HttpURLConnection,就可以将数据发送到服务器了(如果需要,但看起来就像它一样,因为你有POST请求):

DataOutputStream wr = new DataOutputStream(httpCon.getOutputStream());
wr.writeBytes(yourData);
wr.flush();
wr.close();

然后您可以检查响应代码(例如,如果它是200):

int responseCode = httpCon.getResponseCode();

从响应中读取数据:

BufferedReader in = new BufferedReader(
                new InputStreamReader(httpCon.getInputStream()));
String line;
StringBuffer response = new StringBuffer();

while ((line = in.readLine()) != null) {
    response.append(inputLine);
}
in.close();

如果您要解析JSON,可以使用org.jsonGson