I wanted to get the plain string, not JSON. The code at client side:
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.TEXT_PLAIN));
HttpEntity<String> entity = new HttpEntity<String>("", headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> tickerResponse = restTemplate.exchange(serviceBase, HttpMethod.GET, entity,String.class);
It works well in local unit test. The log looks like:
08:24:46,291 DEBUG RestTemplate:598 - Setting request Accept header to
[text/plain, /]
However, it doesn't work in tomcat, the log was:
08:20:48,362 DEBUG RestTemplate:598 - Setting request Accept header
to [application/json, application/*+json, text/plain, /]
I guess RestTemplate set the Accept Header to JSON by default when running in my Tomcat 8. How to clean the default settings?
Related
I am trying to consume a third party REST API using Spring's RestTemplate component. I have tried entering the same request on an external REST API Client (Postman) - using the same URI and custom headers and I am able to retrieve the correct data.
However, when I tried to mirror the exact request using RestTemplate, it returns me
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved here.</p>
<hr>
<address>Apache/2.4.7 (Ubuntu) Server at address Port 80</address>
</body></html>
This is a sample of the code I am using:
String uri = "http://address/{path of endpoint}";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set(someCustomHeaderKey, someCustomHeaderValue);
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);
I have read that java does not allow redirect from one protocol to another, for instance, from http to https and vise versa. Would require some help on the approach on this.
RestTemplate will follow redirects by default, but not if the protocol is different,
which is the situation that you are seeing (redirecting from http to https).
For a more full explanation, and code that makes this work, see
HTTPURLConnection Doesn't Follow Redirect from HTTP to HTTPS
I have tried your code on my local machine and everything seems fine.
302 status code is indicating that your URI location is different.
as per your example, you should use https instead of Http in URI
I have tried your code as below
String uri = "https://jsonplaceholder.typicode.com/todos/1";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.set("link", "http/:");
HttpEntity<String> entity = new HttpEntity<String>(headers);
ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET,
entity, String.class);
System.out.println(response);
output in console
<200,{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},[Date:"Thu, 12 Mar 2020 03:45:44 GMT", Content-Type:"application/json; charset=utf-8", Content-Length:"83", Connection:"keep-alive", Set-Cookie:"__cfduid=d3104b8bbd25cbcb802977fc9183d559e1583984744; expires=Sat, 11-Apr-20 03:45:44 GMT; path=/; domain=.typicode.com; HttpOnly; SameSite=Lax", X-Powered-By:"Express", Vary:"Origin, Accept-Encoding", Access-Control-Allow-Credentials:"true", Cache-Control:"max-age=14400", Pragma:"no-cache", Expires:"-1", X-Content-Type-Options:"nosniff", Etag:"W/"53-hfEnumeNh6YirfjyjaujcOPPT+s"", Via:"1.1 vegur", CF-Cache-Status:"HIT", Age:"1747", Accept-Ranges:"bytes", Expect-CT:"max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"", Server:"cloudflare", CF-RAY:"572a862eab83d5e8-BOM"]>
I am trying to do post request to a rest service (https).
Everything works fine in postman although RestTemplate.exchange always returns 401 - unauthorized.
The body and the headers are the same.
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("client_id", clientId);
httpHeaders.add("api_key", authToken);
// httpHeaders.add("Authorization", "Basic " + authToken); - also tried
HttpEntity<?> requestEntity = new HttpEntity<>(request, httpHeaders);
return restTemplate.exchange(getUrl(), httpMethod, requestEntity, responseType).getBody();
I've tried to skip ssl verification, also tried this solution: Spring Boot RestTemplate Basic Authentication using RestTemplateBuilder, it doesn't help.
Any ideas what I am missing?
I am using exchange method of RestTemplate as below but it doesn't encode some characters right.
Original value is : <Description>Salih'in firewallişççöı ımçööşöşöğ</Description>
Sent value is:<Description>Salih'in firewalli?���? ?m���?�?�?</Description>
Headers are as follows:
Content-Type : application/vnd.vmware.admin.edgeGatewayServiceConfiguration+xml; charset=ISO-8859-1
Accept : application/*+xml;version=5.6
This is how i make the request
restTemplate.setErrorHandler(new RequestErrorHandler());
restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
apiResponse = restTemplate.exchange(url, vCloudRequest.getHttpMethod(), entity, responseType);
The problem was that RestTemplate was using charset=ISO-8859-1 which is given in the Content-Type header.
It is checking the Content-Type header if any charset is specified and if so it uses that charset.
I'm making an app and trying to get json written on the web page. So, I can see this page in browser: it contains only json.
But when I start a request with the RestTemplate it returns ma only 500 internal server error.
My caode is very simple:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> requestEntity = new HttpEntity<>(requestHeaders);
ResponseEntity<MyClass[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, MyClass[].class);
I cannot understand what is wrong: I have an access, it is simple, I'm not authentificated and I don't need id. Why an error?
The 500 Internal Server Error means something has gone wrong on the server side...
You should check your URL, parameter, cookies, etc... (in firebug by example)
I test your code and i got a 200 status on a valid URL.
I am writing a Rest client to post JSON data using Spring RestTemplate.
Using POSTMAN and following JSON data in body get the response correctly-
{
"InCode":"test",
"Name":"This is test",
"Email":"test#gmail.com",
"Id":18,
}
However when trying to hit the REST API using Spring RestTemplate as follows
ResponseEntity<String> response = restTemplate.exchange(baseUrl,
HttpMethod.POST, getHeaders(), String.class);
private HttpEntity<?> getHeaders() throws JSONException {
JSONObject request = new JSONObject();
request.put("Email", "test#gmail.com");
request.put("Id", "18");
request.put("Name", "This is test");
request.put("InCode", "test");
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
return new HttpEntity<>(request.toString(), headers);
}
I get the exception-
11:52:56.808 [main] DEBUG o.s.web.client.RestTemplate - Created POST request for "http://server-test/platform/v4/org"
11:52:56.815 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, application/json, application/*+json, */*]
12:03:47.357 [main] DEBUG o.s.web.client.RestTemplate - Writing [{"InCode":"test","Email":"test#gmail.com","Id":"18","Name":"This is test"}] using [org.springframework.http.converter.StringHttpMessageConverter#6a1aab78]
11:52:57.574 [main] DEBUG o.s.web.client.RestTemplate - POST request for "http://server-test/platform/v4/org" resulted in 500 (Internal Server Error); invoking error handler
Exception in thread "main" 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.handleResponse(RestTemplate.java:641)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475)
Would be thankful for any help.
You are setting the 'Accept' header, which defines which content type you will accept as a response.
Instead you must set the header 'Content-Type' with 'application/json'.
Edit:
In your java code id is a string, in the postman its a number.
May be this makes the server fail?
Try this way
try {
return restTemplate.exchange(url, httpMethod, httpEntity, String.class);
} catch(HttpStatusCodeException e) {
return ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
.body(e.getResponseBodyAsString());
}
I was facing the same problem. After printing the request and URL, I found that I was using a wrong endpoint. Can you please try to print the URL in the logs and check if that is correct?