I am currently working on renewing youtrack api methods in the project since old youtrack api has been deprecated, and when I'm trying to send requsts such as:
https://youtrack.my.ru/api/admin/customFieldSettings/bundles/version/
https://youtrack.my.ru/api/issues?query=sampletext
and I am getting
400 HTTP method POST is not supported by this URL
Thr problem is not in the requsts itself, because i tryed using the same requests with the same bodies and headers via postman and it worked perfectly, so i assume it is something with my java restTemplate config, you can se samples of me sending requests below:
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.POST, versionsEntity, String.class);
logger.debug("Adding new version response status is {}", response.getStatusCode());
return response.getStatusCode() == HttpStatus.CREATED;
And this is how I add body to the requst (the body is the versionBundle object):
versionsEntity = new HttpEntity<>(new ObjectMapper().writeValueAsString(versionBundle), entity.getHeaders());
You can also see that youtrack api itself is perfectly ok with me using POST requst to update a bundle here: https://www.jetbrains.com/help/youtrack/devportal/operations-api-admin-customFieldSettings-bundles-version.html#update-VersionBundle-method
Any help is appreciated!
Somehow problem was resolved by creating new RestTemplate with autowired templateFactory, before i was autowiring RestTemplate, if someone can explain me why is this helped it would be great
Related
I'm new to the java rest CXF client. I will make various requests to a remote server, but first I need to create a Ticket Granting Ticket (TGT). I looked through various sources but I could not find a solution. The server requests that I will create a TGT are as follows:
Content-Type: text as parameter, application / x-www-form-urlencoded as value
username
password
I create TGT when I make this request with the example URL like below using Postman. (URL is example). But in the code below, I'm sending the request, but the response is null. Could you help me with the solution?
The example URL that I make a request with POST method using Postman: https://test.service.com/v1/tickets?format=text&username=user&password=pass
List<Object> providers = new ArrayList<Object>();
providers.add(new JacksonJsonProvider());
WebClient client = WebClient.create("https://test.service.com/v1/tickets?format=text&username=user&password=pass", providers);
Response response = client.getResponse();
You need to do a POST, yet you did not specify what your payload looks like?
Your RequestDTO and ResponseDTO have to have getters/setters.
An example of using JAX-RS 2.0 Client.
Client client = ClientBuilder.newBuilder().register(new JacksonJsonProvider()).build();
WebTarget target = client.target("https://test.service.com/v1/tickets");
target.queryParam("format", "text");
target.queryParam("username", "username");
target.queryParam("password", "password");
Response response = target.request().accept(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.entity(yourPostDTO,
MediaType.APPLICATION_JSON));
YourResponseDTO responseDTO = response.readEntity(YourResponseDTO.class);
int status = response.getStatus();
Also something else that can help is if you copy the POST request from POSTMAN as cURL request. It might help to see the differences between your request and POSTMAN. Perhaps extra/different headers are added by postman?
Documentation: https://cxf.apache.org/docs/jax-rs-client-api.html#JAX-RSClientAPI-JAX-RS2.0andCXFspecificAPI
Similar Stackoverflow: Is there a way to configure the ClientBuilder POST request that would enable it to receive both a return code AND a JSON object?
I'm able call 4-5 rest apis, prior to coming to this block of code. But I'm not able to execute this block of code.
I am using spring 4.0.4 core, mvc jars.
I am trying to call a azure ucwa web service using rest template, its a post method with string as body. I m getting a 500 internal error. I have searched all over internet and yet did not find solution, Please guide me. Thank you.
link : https://learn.microsoft.com/en-us/skype-sdk/ucwa/sendanim
step 9
RestTemplate restTemplate = new RestTemplate();
System.out.println(" jsonLinksObj : 4a "+jsonLinksObj);
org.json.JSONObject jsonSendMessageObj = jsonLinksObj.getJSONObject("sendMessage");
String sendMsgFullUrl = poolUrl.concat(jsonSendMessageObj.getString("href")).concat("?OperationContext=4322131");
headers.clear();
headers.setContentType(MediaType.TEXT_PLAIN);
headers.set("Authorization", "Bearer " + jwtToken);
String body = "My Send Message Here";
HttpEntity<Object> entityJsonSendMsg4 = new HttpEntity<Object>(body, headers);
ResponseEntity<Object> sbSendMsgObj = null;
try{
sbSendMsgObj = restTemplate.exchange(
new URI(sendMsgFullUrl),
HttpMethod.POST,
entityJsonSendMsg4,
Object.class);
} catch(Exception e){
e.printStackTrace();
}
WARN : org.springframework.web.client.RestTemplate - POST request for "https://webpoolpnqin102.infra.lync.com/ucwa/oauth/v1/applications/102086376449/communication/conversations/46db8085-8ad0-4186-a4f0-9a521b256b9b/messaging/messages?OperationContext=4322131" resulted in 500 (Internal Server Error); invoking error handler
org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:589)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:547)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:518)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:463)
at com.test.example.employee.test.EmployeeTest.sendMessage(EmployeeTest.java:266)
at com.test.example.employee.test.EmployeeTest.main(EmployeeTest.java:337)
Exception in thread "main" java.lang.NullPointerException
at com.test.example.employee.test.EmployeeTest.sendMessage(EmployeeTest.java:331)
at com.test.example.employee.test.EmployeeTest.main(EmployeeTest.java:337)
It is hard to say what is the reason behind the 500 you got in response - you probably have to debug it yourself but it should not be very hard.
Since you created RestTemplate using default constructor you have got a deafault error handling. Run your application in debug mode and place a breakpoint in DefaultResponseErrorHandler::handleError. There you get the access to response represented by ClientHttpResponse class and can actually look into body you got back.
When you know the reason behind the error you can correct the request accordingly.
I have clean and build the project. And run the code again. Its working fine, anybody want to send string in body, can use the above rest template code. Thank you.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
HTTP GET with request body
I've read few discussions here which do not advocate sending content via HTTP GET. There are restrictions on the size of data that can be sent via clients (web browsers). And handling GET data also depends on servers. Please refer section Resources below.
However, I've been asked to test the possibility to send content via HTTP GET using RestTemplate. I refered few discussions on spring forum but they were not answered. (Please note sending data via http Post works fine). The discussion here suggests using POST instead.
dev env - JBoss AS 5.1, Spring 3.1.3
Client
#Test
public void testGetWithBody()
{
// acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.TEXT_PLAIN);
// header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
// body
String body = "hello world";
HttpEntity<String> entity = new HttpEntity<String>(body, headers);
Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("id", "testFile");
// Send the request as GET
ResponseEntity<String> result = restTemplate.exchange(
"http://localhost:8080/WebApp/test/{id}/body",
HttpMethod.GET, entity, String.class, uriVariables);
Assert.assertNotNull(result.getBody());
}
Server #Controller
#RequestMapping(value = "/{id}/body", method = RequestMethod.GET)
public #ResponseBody
String testGetWithBody(#PathVariable String id,
#RequestBody String bodyContent)
{
return id + bodyContent;
}
The problem -
executing this test case returns 500 Internal Server Error. On debugging, I found that the controller is not hit.
Is it correct to understand that the RestTemplate provides the way to send data as request body, but the error occurs because the server could not handle the request body ?
If the request body sent via HTTP Get is not conventional why does RestTemplate provide the APIs to allow sending it ? Does this mean there are few servers capable of handling the Request body via GET ?
Resources - discussions on sending body via HTTP GET using RestTemplate at spring forum
http://forum.springsource.org/showthread.php?129510-Message-body-with-HTTP-GET&highlight=resttemplate+http+get
http://forum.springsource.org/showthread.php?94201-GET-method-on-RestTemplate-exchange-with-a-Body&highlight=resttemplate+http+get
Resources - General discussions on sending body via HTTP GET
get-with-request-body
is-this-statement-correct-http-get-method-always-has-no-message-body
get-or-post-when-reading-request-body
http-uri-get-limit
Is it correct to understand that the RestTemplate provides the way to send data as request body, but the error occurs because the server could not handle the request body ?
You can tell by looking at network traffic (does the request get sent with a request body and a GET method?) and at server logs (the 500 result you receive must have a server-side effect that gets logged, and if not, configure the server to do so).
If the request body sent via HTTP Get is not conventional why does RestTemplate provide the APIs to allow sending it ? Does this mean there are few servers capable of handling the Request body via GET ?
Because it is a generic class that also allows you to craft requests that can include a message body.
As stated in HTTP GET with request body:
In other words, any HTTP request message is allowed to contain a message body, and thus [a server] must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics.
A body on a GET cannot do anything semantically, because you are requesting a resource. It's like you tell the server: "Give me resource X, oh, and have some apples!". The server won't care about your apples and happily serve resource X - or throw an error because it doesn't like any offers in a request.
However, I've been asked to test the possibility to send content via HTTP GET
Please tell the one who requested this that this is a case that should not have to be tested, because no sensible implementation supports it.
I am experiencing a weird issue when working with RestTemplate. I'm using a certain REST API and there I want to update something using PUT.
Thus, in e.g. Postman I am sending this request:
PUT http://fake/foobar/c/123 with a certain body
This update via Postman is successful. If I now execute the same call in Java via a RestTemplate, I am getting a 405 Method Not Allowed:
HttpHeaders headers = createHeader();
HttpEntity<Offer> httpEntity = new HttpEntity<>(bodyEntity, headers);
String url = "http://fake/foobar/c/123"; //Created dynamically, but here pasted for sake of simplicity
RestTemplate restTemplate = new RestTemplate(...);
ResponseEntity<OfferResponse> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, OfferResponse.class);
...
I compared the URL again and again. If I copy the URL logged in the console and copy it to Postman, I can do the update successfully. I also compared the headers and everything. Everything is equal to how it is done via Postman.
Is there any potential other reason for such a behavior (another reason than I am too stupid comparing the headers etc. and missing something)? Other PUT, POST calls etc. against this API are working fine, otherwise I would have assumed that there is a general problem with my usage of RestTemplate
Code 405 Method Not Allowed means the HTTP verb (GET, POST, PUT, etc.) you use against this end-point is known but not accepted by the API.
If you can't post the details of your API as #Dinesh Singh Shekhawat suggested, I will first try to use Postman Code feature and get an automatically generated code for Java (OkHTTP or UniRest) of the request. You can find this option on the right part below the Send button. Copy this code and try to perform the request.
Then compare this request with yours.
You can always use HttpPut instead of RestTemplate if it's not a requirement:
HttpClient client = HttpClientBuilder.create().build();
String url = "http://fake/foobar/c/123";
HttpHeaders headers = createHeader();
HttpEntity<Offer> httpEntity = new HttpEntity<>(bodyEntity, headers);
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(httpEntity);
HttpResponse response = client.execute(httpPut);
I was facing the same problem. Later I printed the request and URL in the logs.
I found that I was using a wrong endpoint.
Can you please try to print the URL and the request in the logs and check if those are expected and correct?
Just in case it helps someone else: I was encountering the same issue and for me it was just the issue of a trailing slash / on the URL. In insomnia (similar to postman) I had a trailing slash, in code I didn't. When I added the slash to my code everything worked.
failure: http://localhost:8080/api/files
success: http://localhost:8080/api/files/
Of course it could also be the other way around, so just double check the actual api definition.
I'm trying to do a HTTP DELETE request with body with Spring RestTemplate via exchange method but I always get a 400 Bad Request like this question. With JavaScript and other tools it is posible to make this API call with DELETE.
I know java <1.8 doesent support DELETE with body, but with 1.8 it should be able: see here. I'm using spring-web-4.2.6.RELEASE with jdk 1.8 so I think there must be a way.
My code:
public DealResponse closePosition(DealCloseRequest dealCloseRequest) {
try {
ObjectMapper mapper = new ObjectMapper();
//Object to JSON in String
String jsonInString = mapper.writeValueAsString(dealCloseRequest);
HttpEntity<String> entity = new HttpEntity<String>(jsonInString, this.headers);
//execute request
ResponseEntity<DealResponse> response = restTemplate.exchange("https://" + this.domain + "/gateway/deal/positions/otc", HttpMethod.DELETE, entity, DealResponse.class);
//return filled DealResponse object
return response.getBody();
} catch (JsonProcessingException e) {
this.logger.warn("could not close Position because: "+e);
return null;
}
}
Error message:
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
Does anyone know a way to do this with spring restTemplate?
HTTP DELETE request with body works fine with rest template for Spring 4.2 release. There could be some issue with request body you are sending to your service. Can you check "jsonInString" if it is forming correct json payload.Check the headers as well for "application/json" type. You can verify your service using Postman by sending DELETE request.