My program calls an external API. Now I want to return this response directly to the user without any changes. But instead of the response where Im supposed to see the header and body, I only get this response:
{
"redirect": false,
"successful": true
}
My code looks like this:
try (Response response = client.newCall(request).execute()) {
return response;
}
When I look at the response object in debug mode, I get all the information I want. Why can't the user see it?
Thanks in advance
The try block automatically closes the response when leaving its scope. Mitigate by reading the response inside that block or getting rid of the try block.
Related
I have been struggling to simply perform a GET request to the Spotify API and parse the results of the request. I haven't been able to successfully do it despite trying to follow the docs. I am trying to achieve this within an Actor. I have tried making the HttpEntity a strict HttpEntity but this returns an error. I am not sure if this is due to dependency issues or if it is simply the incorrect approach. What I would like to do is obtain the entire payload of the response and parse it to then return it to another actor. I am unsure what should go inside of the try block to achieve this. Thanks very much.
ActorSystem actorSystem = getContext().getSystem();
Http http = Http.get(actorSystem);
String endpoint = "https://api.spotify.com/v1/artists/1moxjboGR7GNWYIMWsRjgG/top-tracks?market=IE";
Authorization authorization = Authorization.oauth2("REDACTED");
HttpRequest request = HttpRequest.create().withUri(endpoint).addHeader(authorization);
CompletionStage<HttpResponse> responseFuture = http.singleRequest(request)
responseFuture.thenAccept(response -> {
try {
}
Have tried casting entity to a strict entity but this results in an error.
I am trying to use littleproxy-mitm to inspect traffic. I have access to the headers and can easily read them. However, I cant find the body of a response consitently. To see if I can get the body I am using this testing my app by visiting https://www.google.com/humans.txt, but the wanted body is no where to be found. But when I visit other sites like google, facebook and twitter I seem to get gibberish(encoded body gzip most prob) and sometimes html.
Here is the filter:
#Override
public HttpObject serverToProxyResponse(HttpObject httpObject) {
if(httpObject instanceof FullHttpResponse){
System.out.println("FullHttpResponse ----------------------------------------");
FullHttpResponse response = (FullHttpResponse) httpObject;
CompositeByteBuf contentBuf = (CompositeByteBuf) response.content();
String contentStr = contentBuf.toString(CharsetUtil.UTF_8);
System.out.println(contentStr);
}
return httpObject;
}
Any idea why I am unable to get body from https://www.google.com/humans.txt ?
To answer my own question.
This code snippet works and will print the whole response. But the reason I was not getting the body response is either the header "Modified-since.." or the "Cache-control: public".
Am new to API testing. I wanted to validated the response body of the GET method. But it is returning the io.restassured.internal.RestAssuredResponseImpl#35adf623 with the below code. Please let me know how can I resolve this. With POST Method, it works fine. Failing with GET method provided am passing all other values correct.
public static Response getResponseWithGetMethod() throws Exception {
Response response = RequestInvoker.invokeGET();
return response;
}
Output :
io.restassured.internal.RestAssuredResponseImpl#35adf623
Expected output is :
{
"path1": true,
"path2": true,
"path3": true
}
Use the body() method to get access to the body of the response.
Response object has multiple fields in it like, body, headers, status code, cookies etc.,
Check out the complete java doc here.
Answer to your code is to call getResponseWithGetMethod().body() or getResponseWithGetMethod().asString(); later one might be appropriate for you.
I use httpResp.sendError(400, "You are missing customer id") to send the response back
When I try to retrieve the message on the client side (using Rest template to call the endpoint).
However, printing the HttpClientErrorException always produces the following result for me:
HttpClientErrorException: 400 null
I see that I have HttpClientErrorException.getResponseBody has all the information about time stamp, message etc. But HttpClientErrorException.getStatusText is always empty.
My question is : How do you design your ResponseEntity on the server-side such that the HTTP client finds the server-side exception message in response.getStatusText() instead of null?
here is the code I have
try{
ResponseEntity<String> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, String.class );
System.out.println(responseEntity.getBody());
}
catch (HttpClientErrorException | HttpServerErrorException e) {
if (e.getStatusCode().equals(HttpStatus.UNAUTHORIZED) || e.getStatusCode().equals(HttpStatus.FORBIDDEN)) { System.out.println("Response Body returned:");
System.out.println(e.getResponseBodyAsString());
System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
System.out.println("Status text is:");
System.out.println(e.getStatusText());
} else if (e.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
System.out.println("Response Body returned:");
System.out.println(e.getResponseBodyAsString());
System.out.println("-------------------------------");
System.out.println("Status text is:");
System.out.println(e.getStatusText());
} else {
throw e;
}
}
Sprint Boot Version: 2.1.0.RELEASE
I traced the code for how RestTemplate actually makes the calls. Basically what happens is the result of HttpClientErrorException.getStatusText() is populated by the HTTP status code's text and not your custom error message. For example, instead of just returning back error code 400, a server might return back error 400 Bad Request. Instead of status code 200, a server might return back 200 OK. If the server responds back with that optional text, that's what you'll see when you call getStatusText(). Note that that text like OK and Bad Request can't be customized by you on the server side.
This is happening because, internally, Spring is making use of SimpleClientHttpResponse.getStatusText() which is internally relying on HttpUrlConnection.getResponseMessage(). As you can see from getResponseMessage's Javadoc, the possible values returned aren't meant to be custom error messages. Note that in your case, getStatusText() is returning null because your server is just sending back a status line like 400 and not 400 Bad Request. You can also see this from the Javadoc. You can probably configure your server to send back status code text messages, but doing so still won't help you use the getStatusText() method to get your custom error message.
Consequently, the HttpClientErrorException.getStatusText() just isn't what you need. Instead, you need to continue calling getResponseBodyAsString(). However, if you know the format of the response body that is sent back from the server (since this will likely be wrapped in HTML and other stuff) you can use a regex to filter out the non-useful parts of the response message.
I want to extract the HTTP status of a HAPI FHIR create Method.
MethodOutcome outcome = client.create().resource(medicationOrders[0]).prettyPrint().encodedXml().execute();
Is there any way to recover it from the MethodOutcome or any other workaround exists?
There are a few things that can be useful..
If the method returns successfully, then you have gotten an HTTP 2xx response back. There isn't a way to tell if it was a 200 or a 204 for example, but it was a successful response.
If the method throws a BaseServerResponseException of some sort, the server returned a 4xx or 5xx status code. You can call BaseServerResponseException#getStatusCode() to find out which one.
If you need to know the exact response in all cases, you can use a client interceptor to find that.
You can obtain status code using Kotlin like this with client interceptors,
Create an interceptor to pick status codes,
private fun createClientInterceptor(statusCodes: MutableList<Int>):
IClientInterceptor {
return object : IClientInterceptor {
override fun interceptRequest(theRequest: IHttpRequest?) {}
override fun interceptResponse(theResponse: IHttpResponse?) {
if (theResponse != null) {
println(theResponse.status)
}
}
}
}
Create a client and register the interceptor
val ctx = FhirContext.forR4()!!
val restfulGenericClient = ctx.newRestfulGenericClient(getServerUrl())
restfulGenericClient.registerInterceptor(createClientInterceptor(statusCodes))
In this way, you can collect status codes of responses in Kotlin, appropriately you can change the code to Java as well.