reading JSON response as string using jersey client

前端 未结 4 1013
有刺的猬
有刺的猬 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:45

    I was able to find solution to the problem. Just had to call bufferEntity method before getEntity(String.class). This will return response as string.

       clientResp.bufferEntity();
       String x = clientResp.getEntity(String.class);
    
    0 讨论(0)
  • 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;
            }
        }
    
    0 讨论(0)
  • 2021-02-20 07:51

    Although the above answer is correct, using Jersey API v2.7 it is slightly different with Response:

    Client client = ClientBuilder.newClient();
    WebTarget target = client.target("http://localhost:8080");
    Response response = target.path("api").path("server").path("ping").request(MediaType.TEXT_PLAIN_TYPE).get();
    System.out.println("Response: " + response.getStatus() + " - " + response.readEntity(String.class));
    
    0 讨论(0)
  • 2021-02-20 07:59

    If you still got problem with this, you may want to consider to use rest-assured

    0 讨论(0)
提交回复
热议问题