0

I have a class that implements Route interface (package spark) that is supposed to return a String in the handle function. When I convert the response to String I have two extra " in the beginning and the end of my String and the \n is not recognized as 1 char in my String but rather as 2. Does anyone know the fix?

This is the code and response is an instance of HttpResponse:

Assert.assertEquals(200, response.getStatusLine().getStatusCode());
String output = EntityUtils.toString(response.getEntity())

The next Assertion fails

Assert.assertEquals(10, output.length());
Java.lang.AssertionError: 
Expected :10
Actual   :13

And according to System.out output is

"123456789\n"

While it should be 123456789 and a \n at the end of it but I don't believe \n should be shown in System.out.print()

user10938362
  • 3,648
  • 2
  • 10
  • 27
Peggy
  • 395
  • 6
  • 21

3 Answers3

0

This may help,

HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);

Reference from - How can I get an http response body as a string in Java?

suketup
  • 459
  • 7
  • 12
0

This question and answers may help: HttpClientErrorException 400 null using RestTemplate in microServices

Basically I am recommending to use a 3d party library that handles http requests/responses for you Here is a copy of relevant part of my answer to that question:
You can use a 3-d party library that sends Http request and handles the response. One of the well-known products would be Apache commons HTTPClient: HttpClient javadoc, HttpClient Maven artifact. There is by far less known but much simpler HTTPClient (part of an open source MgntUtils library written by me): MgntUtils HttpClient javadoc, MgntUtils maven artifact, MgntUtils Github. Using either of those libraries you can send your REST request and receive response independently from Spring as part of your business logic

Michael Gantman
  • 5,975
  • 1
  • 17
  • 34
0

So this is what solved it for me at the end, if anyone else has the same problem:

String output = EntityUtils.toString(response.getEntity())
String content = new Gson().fromJson(output, String.class);
Peggy
  • 395
  • 6
  • 21