REST Assured returns response of "No HTTP resource was found that matches the request URI '****/api/Document/getBrowserData'" - httpresponse

I have implemented my REST Assured code like below
String tempUrl = "***/api/Document/getBrowserData";
Response rjson = given()
.param("dsId",1108)
.param("isNew", false)
.param("oToken","eed0361d314888a3f153534844869d9f")
.param("projId",837)
.param("tId",-1)
.param("type",2195)
.param("userId",104)
.post(tempUrl)
.then()
.extract()
.response();
System.out.println(rjson.asString());
and when I perform some action on the response:
System.out.println(rjson.asString()); // "Message":"No HTTP resource was found that matches
the request URI '
System.out.println(rjson.getHeaders()); // header value
System.out.println(rjson.getStatusCode()); // 404
But when I do the same thing with PostMan I am able to get a valid response.

Related

sending GET request via REST template with JSON request body getting failed with binding binding element must be a struct error?

I am trying to send a GET request using REST Template with a JSON request body, but the request is failing with error,
processing
failedorg.springframework.web.client.HttpServerErrorException$InternalServerError:
500 Internal Server Error: [code=400, message=binding element must be
a struct]
I have tried hitting the endpoint using the insomnia and the request is going through successfully, There I have put 2 headers
1. Content-Type - application/json
2. Authorization - Bearer ******
And the JSON body.
My code in spring boot looks like this.
ResponseEntity<String> responseObject = null;
String URL = "https://myurl/endpoint";
String requestBody = "{\"requestType\":\"status\"}";
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization","Bearer ***");
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity<>(body,headers);
System.out.println(httpEntity+" httpEntity");
System.out.println(headers+" headers");
responseObject = restTemplate.exchange(URL, HttpMethod.GET, httpEntity, String.class);
The sout for httpentity and header looks like this
httpEntity
<{"requestType":"status"},[Authorization:"Bearer *******************", Content-Type:"application/json"]>
headers
[Authorization:"Bearer *************************", Content-Type:"application/json"]
Also when I am trying to send a request without the body to another endpoint using rest template, that is getting executed successfully, so I think something with the way I am sending the body has to do with the error.
rest template doesn't support get request with body . for more details you can refer this article.
If you are on Java 11 I would suggest you to use java.net.HttpClient which will fulfill your need.

RestController PutMapping malformed url when using "[]"

I have a Spring App witch use a controller like this:
#PutMapping("/block/{blockid}/service/{serviceid}")
public ResponseEntity<String> config(#PathVariable blockid, #PathVariable serviceid, #RequestBody String body) {
{
And I using Postman to test the request, if i send this request to this url:
url: localhost:7000/block/myBlockTest/service/externalServiceTest[0]
Response this error:
Description The server cannot or will not process the
request due to something that is perceived to be a client error
(e.g., malformed request syntax, invalid request message framing, or
deceptive request routing).
I know the problem is "[0]" in the url.
Is there any way I can send this in the URL ?
Thanks.
OK, I just need modify the request to be localhost:7000/block/myBlockTest/service/externalServiceTest%5B0%5D
Special parameters.
https://cachefly.zendesk.com/hc/en-us/articles/215068626-How-to-format-URLs-that-have-special-characters-in-the-filename-

Outh2 Access Token Exception

I am implementing Outh2 for authentication in spring boot application.I am getting the authorization code successfully but when i am making post request to token url by rest template it is giving me exception 400 bad Request.By this exception i am not able to identify the issue.Below is my code.
ResponseEntity<String> response = null;
System.out.println("Authorization Ccode------" + code);
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> request = new HttpEntity<String>(headers);
String access_token_url = "https://www.googleapis.com/oauth2/v3/token";
access_token_url += "?code=" + code;
access_token_url += "&client_id =487786082511-ta7fnptb8dnd4lbq9lphbtbpll9eo1it.apps.googleusercontent.com";
access_token_url += "&client_secret =fS4KHLUUMOm-lYu8QtDOFcDV";
access_token_url += "&grant_type=authorization_code";
access_token_url += "&redirect_uri=http://localhost:8080/salesgoal/googleOuth2Success";
try {
response = restTemplate.exchange(access_token_url, HttpMethod.POST, request, String.class);
}
catch(Exception e){
e.printStackTrace();
Please let me know what i am doing wrong.
Thanks
Following google's oauth2 documentation
Exchange code for access token and ID token
The response includes a code parameter, a one-time authorization code that your server can exchange for an access token and ID token. Your server makes this exchange by sending an HTTPS POST request. The POST request is sent to the token endpoint, which you should retrieve from the Discovery document using the token_endpoint metadata value. The following discussion assumes the endpoint is https://oauth2.googleapis.com/token. The request must include the following parameters in the POST body:
Follwing their documentation there could be validations on the url parameters (which yield the 400 Bad Request error code)
Please check the following:
The redirect_uri is URL_encoded (by using UrlEncoder)
Url parameters don't contain spaces ( checkclient_id and client_secret )
Later Edit:
Also try following oauth2 specification by using 'Content-Type', 'application/x-www-form-urlencoded' headers on the /token request

axios request to put jersy service does not work

I have a very frustrating problem. I have a my put servive in jersy and I call it via axios. Here is my code for jersy:
#PUT
#Path("/{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response update(#PathParam("id") int id, String jsonRequest) {
return new UpdateController().updateUser(id, jsonRequest);
}
Here is how I call it in the front end:
axios.put(putURL, newUserPreferences)
.then(response => {
.
.
So if I call it with the avobe put request I get the following error code:
Failed to load puturl...: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3003' is therefore not allowed access. The response had HTTP status code 403.
Can anyone help why it is happening?

Spring + Angular: How to parse ResponseEntity in angular?

I'm using Spring Boot to create an API that needs to be consumed in Angular 4. Spring and Angular are on different ports.
The problem is that Spring's ResponseEntity raises an error in Angular.
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity getFlow(#PathVariable int id) {
Flow flow = flowService.findById(id);
return new ResponseEntity(flow, HttpStatus.FOUND);
}
Now, I can perfectly use Postman to test the API and it works.
But when I make a request from Angular, it returns an error:
Strangely, it returns an error alongside the requested object.
Now, the cause of the problem is that the Spring Boot application returns a ResponseEntity and not a normal object (like String), and Angular doesn't know how to interpret it. If the controller returns just a Flow object, it works.
How can it be solved using ResponseEntity? Or, how else can I send the object alongside the HTTP status code?
Also, in #RequestMapping put produces = "application/json", and in get request in angular, add http options :
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
};
So your get request looks like this:
this.http.get(url, httpOptions)
As per the document mentioned here
https://docs.angularjs.org/api/ng/service/$http
A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the outcome (success or error) will be determined by the final response status code.
As you are sending an instance of ResponseEntity(HttpStatus.Found) whose Http status code is 302 which doesnt fall under the success range thats why error callback is called.
Try returning the content like this
return new ResponseEntity(flow, HttpStatus.OK);

Resources