I am having some issues trying to receive a response message from a Spring RESTful web service to an AngularJS client.
I am using ResponseEntity<String> to return a response to the client. This works when only returning a status code but AngularJS fails with Unexpected token R when I send a response message in the body.
What am I doing wrong?
return new ResponseEntity<String>(HttpStatus.OK);
But this does not work:
return new ResponseEntity<String>("Report was updated successfully", HttpStatus.OK);
AngularJs code:
$http.get(url, header)
.success(function(data, status, headers, config) {
// some logic
}).error(function(resp, status) {
// some logic
});
Response:
Is Angular expecting JSON or HTML/text back?
I've experienced issues in the past returning text/javascript or application/json instead of text/html. It looks like Angular is expecting JSON or JSONP in that instance, hence the Unexpected Token R (which is the first letter of your response string).
I could give a more precise answer, but I'd need to also know if you're using JSONP vs JSON, etc.
Related
I need to consume a vendor API which returns file(.pdf/.jpg/.png) in binary format when request succeeds while returns a JSON Response when Request fails.
The Request method is of type POST.
I tried using below code:
WebClient webClient = WebClient.create();
ResponseEntity<Object> apiResponse = webClient.post()
.uri(new URI("https://api.myapp.in/getDocument"))
.header("mobile", "XXXXXXXXX8")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
//.accept(MediaType.parseMediaType("application/pdf"))
.body(BodyInserters.fromFormData(map))
.retrieve()
.toEntity(Object.class)
.block();
When i execute the above code it works fine and i am able to get the JSON Response for Error case but when the request is success it gives error as below:
Content type 'application/pdf' not supported for bodyType=java.lang.Object
Once your get Response, you can ResponseEntity.getHeaders().
From the response headers you can get the content type and consume your response accordingly.
If API does not return valid content-type based on the response, you can raise a defect on the API provider.
I am trying to build a Rest API automation based on Java, RestAssured, and Cucumber. I ' trying to hit an endpoint via POST. The problem is when I am converting the response as string and when I print the response, it is printing the XML file contents but not the response. I also see the status code as 200. I'm not sure what is going wrong in here. Below is the sample snippet from my codebase.
I am trying to hit a WebService (SOAP WSDL).
// required imports
public class Service_Steps {
Response xmlResponse;
#When("I create a POST request for RCP for endpoint using XML")
public void i_create_a_post_request_for_endpoint_using_xml() {
// xml Request body
String path = "pah_to_xml_file";
File file = new File(path);
xmlResponse = RestAssured.given().when().relaxedHTTPSValidation().accept(ContentType.XML).header(<headers>)
.body(file)
.post(url);
String xmlResponseAsString = xmlResponse.then().extract().body().asString();
}
Not sure why I am seeing this ambiguity. Sometimes it is printing the response, and sometimes it is printing the XML file (request body) contents.
After checking with developers I came to know that the SOAP EndPoint is sending out the responses in two different ways, randomly!
Try this one:
xmlResponse = RestAssured.given().log().all().when().relaxedHTTPSValidation().accept(ContentType.XML).header(<headers>)
.body(file)
.post(url)
.then()
.log().all()
.extract()
.response();
This will print out all the request & response stuff
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".
I have GET REST API, which sends some information in response header.
I am writing test case using rest assured framework, issue I am facing is, in response of GET API, I am not getting header string set by the server in rest API response.
I have checked the same API in Rest client and HTTP Resource, there I can see the header information set by server in API response.
But in rest assured Response object, header information set by server is not available.
Rest API code:
#Path("/download")
#GET
#Produces("application/zip")
public Response downloadContractZipFile(#PathParam("contractId") final String contractId) throws CMException{
ContractActionRequest contractActionRequest = new ContractActionRequest();
contractActionRequest.setId(contractId);
DownloadActionResponse downloadActionResponse = (DownloadActionResponse) executeAction(Action.DOWNLOAD, contractActionRequest);
Response res = Response
.ok(downloadActionResponse.getFilestream(), MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition",downloadActionResponse.getContentDisposition())
.header("Expires", "0")
.header("Content-Length", String.valueOf(downloadActionResponse.getContentLength()) )
.build();
return res;
}
Above you can see, API is returning Content-Length in header. But when I am invoking above API using rest assured framework, it does not receive "Content-Length" in header. Assert is getting failed.
Rest assured Test case code:
given().get(propertyURI).then().assertThat().header("Content-Length","7562");
java.lang.AssertionError: Expected header "Content-Length" was not "7562", was "null". Headers are:
X-Powered-By=Servlet/3.0
Cache-Control=no-cache, no-store
Cache-directive=no-cache
Pragma=no-cache
Pragma-Directive=no-cache
Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type=text/html;charset=UTF-8
x-authenticated=false
x-location=https://reena:9453/app/login.jsp?targetApp=OM
Content-Language=en-US
Transfer-Encoding=chunked
I suggest you try Karate instead of REST-Assured as it has much better support for validating response headers.
(disclaimer: am Karate dev)
I have a question on how to fetch response body in Jersey client when server returns some sample text with status code 401. Sample service is setup as follows:
#GET
#Path("test401withcontent")
public Response get401TestWithContent()
{
return Response.status(401).entity("return some text").build();
}
On the client side (using Jersey 1.17) ClientResponse.getEntity prints null.
Noticed that content-length of headers has the right number (16 in this case.)
Is there a different way to get response when return code is 401?
Have deployed you method to my test web site and used below client got currect response.
Client client = ClientBuilder.newClient();
//System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
Response response = client.target(
"http://jerseyexample-ravikant.rhcloud.com/rest/jws/test401withcontent").
request().get(); System.out.println(response.readEntity(String.class));