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.
Related
I am sending the following Sig4 request:
Response response = new AmazonHttpClient(new ClientConfiguration())
.requestExecutionBuilder()
.executionContext(new ExecutionContext(true))
.request(request)
.errorResponseHandler(new AWSErrorResponseHandler(false))
.execute(new AWSResponseHandler(false));
I then convert the response to httpResponse: (not sure if its needed)
com.amazonaws.http.HttpResponse httpResponse = response.getHttpResponse();
My issue is that I was unable to find a simple explanation on how to extract the actual JSON response
string out of my response.
EDIT: Note that when I follow the SDK doc and try to extract the content as an input stream:
IOUtils.toString(response.getHttpResponse().getContent());
I get the following exception:
java.io.IOException: Attempted read from closed stream.
at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:165)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:135)
at com.amazonaws.internal.SdkFilterInputStream.read(SdkFilterInputStream.java:90)
at com.amazonaws.event.ProgressInputStream.read(ProgressInputStream.java:180)
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:106)
at com.amazonaws.util.IOUtils.toByteArray(IOUtils.java:44)
at com.amazonaws.util.IOUtils.toString(IOUtils.java:58)
Any assistant would be highly appreciated :)
For HTTP responses I used RestAssured. With this it should work like this:
Response response = new AmazonHttpClient().execute() // build and run your query
String json = response.getBody().prettyPrint();
If you want to use the information of the json directly afterwards within the code I can recommend creating a POJO and then doing the following:
AmazonResponseDto dto = response.as(AmazonResponseDto.class)
A quick look up of the com.amazonaws.http.HttpResponse docs showed me, that you can get an InputStream from it, but not directly a json.
I don't know the package of the Response you used in your first code block, that's why I recommended RestAssured.
I found the reason for my issue. As some have suggested, the response is an input stream, yet when I tried to extract it to starting I either got a closed connection exception or nothing. To fix this I had to change .execute(new AWSResponseHandler(true)); to true instead of false in order to keep the connection open. AWSResponseHandler implements HttpResponseHandler and sets the following:
public AWSResponseHandler(boolean connectionLeftOpen) {
this.needsConnectionLeftOpen = connectionLeftOpen;
}
I hope this helps anyone who gets into a similar situation.
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.
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.
Need your help.
I am using postman and trying to get information in JSON format.
But instead of correct format of message i got this result -> "[]"
I don't have any error and i can print in console the requested information, but can't in the browser. I hope anybody can give me a clue..
#GET
#Path("/{messager_id}")
#Produces(MediaType.APPLICATION_JSON)
public String GetMessageById(#PathParam("messager_id") long id){
String message = new MessageService().getMessageById(id);
return message;
}
I would recommend to first of all, use some webservice client as DHC REST Client (an addon for Chrome browser). Use it and check the real behaviour of your webservice. If the client gets and empty json object, then sure your server is producing empty data. Log the string message to be sure is returning data. If it is correct, check the return method. An example of returning of a webservice can be:
return Response.ok(message, MediaType.APPLICATION_JSON).build();
Check if the content type header is set : Content-type = application/json. Please provide additional information.
One thing to check for is to ensure that the MessageService.getMessageById(id) is returning data.
I want to read post parameters and the body from a http post.
Example:
If you post to the url: http://localhost/controller?sign=true.
In the post there is also json data in the body.
{"transaction":
{"user":[
{"name": "Anna"}]
}
}
Getting the parameter is done via
public java.lang.String getParameter(java.lang.String name)
And the body can be retrieved via
public ServletInputStream getInputStream() throws java.io.IOException
But how do you get in hold of both the parameter and the body?
Because if i call getParameter before getInputStream the result will be -1 on the inputStream.
I believe under the covers of getParameter(String name), the ServletInputStream is being read to get those parameter. If you're going to be mixing POST data with URL parameters (I'm assuming the sign=true is the parameters you mentioned trying to get) use HttpServletRequest.getQueryString() to get the URL parameters, then you should still be able to read the body with getInputStream(). You will probably have to parse through the query string to get the information you're looking for, however.
EDIT: I forgot to add in my original answer that when the ServletInputStream is read, it cannot be read again. If the data from the stream needs to be used multiple times, you'll have to store it.
http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html