reading JSON response as string using jersey client

前端 未结 4 1011
有刺的猬
有刺的猬 2021-02-20 07:20

I am using jersey client to post a file to a REST URI that returns response as json. My requirement is to read the response as is(json) to a string.

Here is the piece of

4条回答
  •  情深已故
    2021-02-20 07:46

    In my case I'm using Jersey 1.19 and Genson got in my classpath somehow? So the accepted answer throws com.owlike.genson.stream.JsonStreamException: Readen value can not be converted to String.

    My solution was to read directly from the response stream:

    private String responseString(com.sun.jersey.api.client.ClientResponse response) {
            InputStream stream = response.getEntityInputStream();
            StringBuilder textBuilder = new StringBuilder();
            try (Reader reader = new BufferedReader(new InputStreamReader(stream, Charset.forName(StandardCharsets.UTF_8.name())))) {
                int c = 0;
                while ((c = reader.read()) != -1) {
                    textBuilder.append((char) c);
                }
                return textBuilder.toString();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    

提交回复
热议问题