How to send LocalDate in RestTemplate parameter - spring

In below I called web service with String parameter named "samana"
String samana= "000ABC";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);
Table res = restTemplate
.exchange("http://localhost:8090/tharindu/findAllComputers?saman=").concat(samana), HttpMethod.GET, requestEntity, Table.class)
.getBody();
How to pass LocalDate parameter in RestTemplate webservice
LocalDate samana = LocalDate.now();
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> requestEntity = new HttpEntity<String>(null, headers);
Table res = restTemplate
.exchange("http://localhost:8090/tharindu/findAllComputers?saman=").concat(samana), HttpMethod.GET, requestEntity, Table.class)
.getBody();

Related

RestTemplate removes cookie. (Migration from CloseableHttpClient)

I need migrate from CloseableHttpClient to RestTemplate in my desctop client application. RestTemplate response has an empty "Set-cookie" header.
Source code (works ok): // returns the Set-Cookie header = "JSESSIONID=D2442..."
List<BasicNameValuePair> parameters = asList(
new BasicNameValuePair("username", username),
new BasicNameValuePair("password", password));
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
CloseableHttpClient client = createDefault()
CloseableHttpResponse response = client.execute(httpPost);
Target code: // returns the Set-Cookie header = ""
String url = url;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<>();
map.add("username", username);
map.add("password", password);
ParameterizedTypeReference<Map<String, String>> responseType = new ParameterizedTypeReference<>() {};
HttpEntity<Object> request = new HttpEntity<>(map, headers);
ResponseEntity<Map<String, String>> tokensInfo = restTemplate.exchange(
url, HttpMethod.POST, request, responseType
);
Help, please.
Add to the target code:
HttpClient httpClient = HttpClientBuilder.create().build();
ClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
restTemplate.setRequestFactory(factory);

spring boot resttemplate api call by providing userid and password

I want to get data from another application controller by providing userid and password.
Getting Error- HTTP Error 405 (Method Not Allowed)
RestTemplate restTemplate = new RestTemplate();
String plainCreds = "USER1:password";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);
ResponseEntity<String> response1 = restTemplate.exchange(uri, HttpMethod.GET, request, String.class);
System.out.println("Result--------"+ response1.toString());

Issue creating stream definitions via rest interface

I want to make sure I am on the right track with this.
I am getting the following response when attempting to create my stream:
015-11-23T08:59:12-0800 1.3.0.RELEASE ERROR qtp1260026681-23 rest.RestControllerAdvice - Caught exception while handling a request
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
at org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping.handleNoMatch(RequestMappingInfoHandlerMapping.java:204) ~[spring-webmvc-4.2.2.RELEASE.jar:4.2.2.RELEASE]
Here is my sample code:
HttpEntity<String> requestEntity;
ResponseEntity<String> responseEntity;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("name", "testStream");
map.add("definition", "file | log");
map.add("deploy", "true");
requestEntity = new HttpEntity<MultiValueMap>(map, headers);
String url = "http://localhost:9393/streams/definitions"
try
{
responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
body = responseEntity.getBody();
statusCode = responseEntity.getStatusCode();
}
catch (Exception e)
{
String test = e.getMessage();
}
Here is the code that returns the: exception is java.util.regex.PatternSyntaxException: Dangling meta character '*' near index 0
*
^
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
def streamName = "TEST";
def url= "http://localhost:9393/streams/definitions";
String definition = "dod-file-source --dir='zxcv' --dir='([^\s]+(\.(?i)(tar))$)' | transform --script=dod.file.transform.groovy --variables='hotfolderId=1' > queue:StorageStream";
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>()
map.add("name", streamName)
map.add("definition", definition)
map.add("deploy", 'true')
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
String body = responseEntity.getBody();
HttpStatus statusCode = responseEntity.getStatusCode();
That is a custom source module dod-file-source but it just adds a few additional features to the file source module
I just ran (a slightly modified version of) your code and had no problems...
HttpEntity<MultiValueMap<String, String>> requestEntity;
ResponseEntity<String> responseEntity;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("name", "testStream");
map.add("definition", "time | log");
map.add("deploy", "true");
requestEntity = new HttpEntity<MultiValueMap<String, String>>(map, headers);
String url = "http://localhost:9393/streams/definitions";
try
{
responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
String body = responseEntity.getBody();
HttpStatus statusCode = responseEntity.getStatusCode();
}
catch (Exception e)
{
e.printStackTrace();
}
2015-11-23T13:00:44-0500 1.3.0.RELEASE INFO task-scheduler-1 sink.testStream - 2015-11-23 13:00:44
2015-11-23T13:00:45-0500 1.3.0.RELEASE INFO task-scheduler-1 sink.testStream - 2015-11-23 13:00:45
2015-11-23T13:00:46-0500 1.3.0.RELEASE INFO task-scheduler-1 sink.testStream - 2015-11-23 13:00:46
2015-11-23T13:00:47-0500 1.3.0.RELEASE INFO task-scheduler-1 sink.testStream - 2015-11-23 13:00:47

Add UTF-8 encoding to ResponseEntity

I have a responseEntity like this one:
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
requestHeaders.setContentType(MediaType.valueOf("text/plain;charset=UTF-8"));
HttpEntity requestEntity = new HttpEntity(jsonQuery, requestHeaders);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
//Not in UTF-8!!
logger.debug("result: " + responseEntity.getBody());
But it's not encoded in UTF-8 and produces characters like this: Soci굩 . Is it possible to make it in UTF-8 or add the encoding somehow in restTemplate?
responseHeaders.add("Content-Type", "text/html; charset=utf-8");
The solution was to add a StringHttpMessageConverter with utf-8 in restTemplate bean like:
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
I've solved the same problem just adding charset=utf8 to my RequestMapping.
Before
#RequestMapping(path = "/{id}", method = RequestMethod.GET, produces = "application/hal+json")
After
#RequestMapping(path = "/{id}", method = RequestMethod.GET, produces = "application/hal+json;charset=utf8")
I add this to my other methods too. I hope this helps.
I have solved this problem. I need to POST a string object in request body with UTF-8.
text/plain
httpHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
applicaton/json
httpHeaders.setContentType(new MediaType("applicaton", "json", StandardCharsets.UTF_8));
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> resposeEntity = null;
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.UTF_8));
HttpEntity<String> httpEntity = new HttpEntity<String>(stringContent, httpHeaders);
responseEntity = restTemplate.exchange(requestUrl, HttpMethod.POST, httpEntity, String.class);
if (HttpStatus.OK.equals(responseEntity.getStatusCode())) {
logger.debug("... success ... result: " + responseEntity.getBody());
}
Alternate approach:
We know that By Default, RestTemplate StringHttpMessageConverter will be ISO-8859-1, So we can convert the response to UTF-8 like this.
String responseDecodedToUTF8 = new String(responseEntity.getBody().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);

How to set an "Accept:" header on Spring RestTemplate request?

I want to set the value of the Accept: in a request I am making using Spring's RestTemplate.
Here is my Spring request handling code
#RequestMapping(
value= "/uom_matrix_save_or_edit",
method = RequestMethod.POST,
produces="application/json"
)
public #ResponseBody ModelMap uomMatrixSaveOrEdit(
ModelMap model,
#RequestParam("parentId") String parentId
){
model.addAttribute("attributeValues",parentId);
return model;
}
and here is my Java REST client:
public void post(){
MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
params.add("parentId", "parentId");
String result = rest.postForObject( url, params, String.class) ;
System.out.println(result);
}
This works for me; I get a JSON string from the server side.
My question is: how can I specify the Accept: header (e.g. application/json,application/xml, ... ) and request method (e.g. GET,POST, ... ) when I use RestTemplate?
I suggest using one of the exchange methods that accepts an HttpEntity for which you can also set the HttpHeaders. (You can also specify the HTTP method you want to use.)
For example,
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
I prefer this solution because it's strongly typed, ie. exchange expects an HttpEntity.
However, you can also pass that HttpEntity as a request argument to postForObject.
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class);
This is mentioned in the RestTemplate#postForObject Javadoc.
The request parameter can be a HttpEntity in order to add additional
HTTP headers to the request.
You could set an interceptor "ClientHttpRequestInterceptor" in your RestTemplate to avoid setting the header every time you send a request.
public class HeaderRequestInterceptor implements ClientHttpRequestInterceptor {
private final String headerName;
private final String headerValue;
public HeaderRequestInterceptor(String headerName, String headerValue) {
this.headerName = headerName;
this.headerValue = headerValue;
}
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().set(headerName, headerValue);
return execution.execute(request, body);
}
}
Then
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add(new HeaderRequestInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
RestTemplate restTemplate = new RestTemplate();
restTemplate.setInterceptors(interceptors);
If, like me, you struggled to find an example that uses headers with basic authentication and the rest template exchange API, this is what I finally worked out...
private HttpHeaders createHttpHeaders(String user, String password)
{
String notEncoded = user + ":" + password;
String encodedAuth = Base64.getEncoder().encodeToString(notEncoded.getBytes());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + encodedAuth);
return headers;
}
private void doYourThing()
{
String theUrl = "http://blah.blah.com:8080/rest/api/blah";
RestTemplate restTemplate = new RestTemplate();
try {
HttpHeaders headers = createHttpHeaders("fred","1234");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
}
catch (Exception eek) {
System.out.println("** Exception: "+ eek.getMessage());
}
}
Calling a RESTful API using RestTemplate
Example 1:
RestTemplate restTemplate = new RestTemplate();
// Add the Jackson message converter
restTemplate.getMessageConverters()
.add(new MappingJackson2HttpMessageConverter());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Basic XXXXXXXXXXXXXXXX=");
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
restTemplate.getInterceptors()
.add(new BasicAuthorizationInterceptor(USERID, PWORD));
String requestJson = getRequetJson(Code, emailAddr, firstName, lastName);
response = restTemplate.postForObject(URL, requestJson, MYObject.class);
Example 2:
RestTemplate restTemplate = new RestTemplate();
String requestJson = getRequetJson(code, emil, name, lastName);
HttpHeaders headers = new HttpHeaders();
String userPass = USERID + ":" + PWORD;
String authHeader =
"Basic " + Base64.getEncoder().encodeToString(userPass.getBytes());
headers.set(HttpHeaders.AUTHORIZATION, authHeader);
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> request = new HttpEntity<String>(requestJson, headers);
ResponseEntity<MyObject> responseEntity;
responseEntity =
this.restTemplate.exchange(URI, HttpMethod.POST, request, Object.class);
responseEntity.getBody()
The getRequestJson method creates a JSON Object:
private String getRequetJson(String Code, String emailAddr, String name) {
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.createObjectNode();
((ObjectNode) rootNode).put("code", Code);
((ObjectNode) rootNode).put("email", emailAdd);
((ObjectNode) rootNode).put("firstName", name);
String jsonString = null;
try {
jsonString = mapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(rootNode);
}
catch (JsonProcessingException e) {
e.printStackTrace();
}
return jsonString;
}
Short solution without HttpHeaders creating:
RequestEntity<Void> request = RequestEntity.post(URI.create(url))
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
// any other headers
.header("PRIVATE-TOKEN", "token")
.build();
ResponseEntity<String> response = restTemplate.exchange(request, String.class);
return response.getBody();
UPDATE: but in case specific headers HttpHeaders become simple:
RequestEntity.post(URI.create(AMOCRM_URL + url))
.contentType(MediaType.APPLICATION_JSON)
.headers(
new HttpHeaders() {{
setBearerAuth(getAccessToken());
}})
.body(...)
Here is a simple answer. Hope it helps someone.
import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;
public String post(SomeRequest someRequest) {
// create a list the headers
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new HttpHeaderInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
interceptors.add(new HttpHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
interceptors.add(new HttpHeaderInterceptor("username", "user123"));
interceptors.add(new HttpHeaderInterceptor("customHeader1", "c1"));
interceptors.add(new HttpHeaderInterceptor("customHeader2", "c2"));
// initialize RestTemplate
RestTemplate restTemplate = new RestTemplate();
// set header interceptors here
restTemplate.setInterceptors(interceptors);
// post the request. The response should be JSON string
String response = restTemplate.postForObject(Url, someRequest, String.class);
return response;
}

Resources