By using rest client
Map<String, String> paramMap = new HashMap<String, String>();
String qqq = g.toJson(query.toString());
paramMap.put("q", "make:chevrolet");
paramMap.put("pretty", "true");
try {
Response response = restClient.performRequest("GET", "vehicles/_search", paramMap);
return EntityUtils.toString(response.getEntity());
Here instead of using map object ,how to build query using the QueryBuilders
Related
I am trying to use WebClient DELETE method. I am making synchronous call for DELETE method.
But, when I am using block() method to get the object. I am getting error.
#Test
public void deleteEmployeeSyncTest() {
log.info("Testing put employee request");
Map<String, String> headersMap = new HashMap<String, String>();
headersMap.put("user", "password");
MultiValueMap<String, String> queryParamsMap = new LinkedMultiValueMap<>();
queryParamsMap.put("idmProperty", Arrays.asList("queryparamavalue"));
Map<String, String> pathParamsMap = new HashMap<>();
pathParamsMap.put("id", "1");
WebClient.ResponseSpec deleteResponse =
restClient.deleteSync(clientIdm, restClientConfig.getEndpoints().get("idm"), "deleteEmployee",
headersMap, pathParamsMap, queryParamsMap);
Employee response = deleteResponse.bodyToMono(Employee.class).block();
log.info("Delete employee response results: {}", response);
//response.subscribe(result -> Assertions.assertNull(result));
}
It gives me error while getting response using block() method call. But, if I use subscribe() method call for Asynchronous transactions, it works.
Here is the error I am getting while running the test case.
org.springframework.web.reactive.function.client.WebClientResponseException$MethodNotAllowed: 405 Method Not Allowed from DELETE http://localhost:8080/test/delete/1?idmProperty=queryparamavalue
at org.springframework.web.reactive.function.client.WebClientResponseException.create(WebClientResponseException.java:204)
I am new to Java (Spring Boot), and i am trying to send a multipart/form-data POST request to s3 to upload a file.
I managed to do this using spring's RestTemplate like this :
public String uploadFile(byte[] file, Map<String, Object> fields, String url) throws URISyntaxException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> formData= new LinkedMultiValueMap<String, Object>();
for (Map.Entry<String, Object> entry : fields.entrySet()) {
formData.add(entry.getKey(), entry.getValue());
}
formData.add("file", file);
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<MultiValueMap<String, Object>>(formData, headers);
String response = restTemplate.postForObject(new URI(url), request, String.class);
return response;
}
Then i tried to do the same using webclient, but i can not and AWS respond with The body of your POST request is not well-formed multipart/form-data.
Here is the code using webclient :
public String uploadFileWebc(byte[] file, Map<String, Object> fields, String url) {
MultipartBodyBuilder builder = new MultipartBodyBuilder();
for (Map.Entry<String, Object> entry : fields.entrySet()) {
builder.part(entry.getKey(), entry.getValue(), MediaType.TEXT_PLAIN);
}
builder.part("file", file).filename("file");
MultiValueMap<String, HttpEntity<?>> parts = builder.build();
Void result = webClient.filter(errorHandlingFilter()).build().post().uri(url)
.contentType(MediaType.MULTIPART_FORM_DATA)
.contentLength(file.length)
.bodyValue(parts)
.retrieve()
.bodyToMono(Void.class)
.block();
return "Done Uploading.";
}
Can anybody please point out what am i missing ?
It turns out that webclient does not add the content-length header due to its streaming nature, and S3 API needs this header to be sent.
I ended up using restTemplate for uploading files to S3.
I have a spring boot application and trying to invoke a rest service of another company by using RestTemplate.
The remote Rest Service required multiple header and body content as Raw JSON.
Here is the sample required body request :
{
"amount": "10000",
"destinationNumber": "365412"
}
But my request body generate like this :
{
amount= [10000],
destinationNumber= [365412]
}
I've done like this :
String BASE_URI = "http://server.com/sericeX";
RestTemplate template = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization","Some token");
headers.add("Content-Type", "application/json");
MultiValueMap<String, String> bodyParam = new LinkedMultiValueMap<>();
bodyParam.add("amount", request.getAmount());
bodyParam.add("destinationNumber",request.getDestinationNumber());
HttpEntity entity = new HttpEntity(bodyParam,headers);
ResponseEntity<TransferEntity> responseEntity = template.exchange(BASE_URI, HttpMethod.POST, entity,TransferEntity.class);
TransferEntity transferEntity = responseEntity.getBody();
Could you please tell me how can i generate body request as JSON ?
Thanks to #Alex Salauyou based on his comment using HashMap instead of MultiValueMap solved the problem. Here is the changes need to be done:
HashMap<String, String> bodyParam = new HashMap<>();
bodyParam.put("amount", request.getAmount());
bodyParam.put("destinationNumber",request.getDestinationNumber());
In all the documentation I found examples for ODataQueryBuilder.
But do you also have an example how to use the Create, Update and Delete methods of the package com.sap.cloud.sdk.odatav2.connectivity:
ODataCreateRequestBuilder
ODataDeleteRequestBuilder
ODataUpdateRequestBuilder
How is the CSRF token handled?
Please provide a working example?
CSRF tokens are fetched with a HEAD request on the metadata endpoint of the OData service.
Some notes:
The following examples assume that you have a destination named "DestinationName" configured in the SAP Cloud Platform cockpit.
Please keep in mind that the S/4HANA virtual data model is usually the easier alternative.
ODataCreateRequestBuilder
Map<String, Object> body = new HashMap<>();
body.put("FirstName", "John");
body.put("LastName", "Doe");
body.put("BusinessPartnerCategory", "1");
ODataCreateRequest createRequest =
ODataCreateRequestBuilder
.withEntity("/sap/opu/odata/sap/API_BUSINESS_PARTNER", "A_BusinessPartner")
.withBodyAsMap(body)
.build();
createRequest.execute("DestinationName");
ODataUpdateRequestBuilder
Map<String, Object> keys = new HashMap<>();
keys.put("BusinessPartner", "12345");
Map<String, Object> params = new HashMap<>();
params.put("FirstName", "John");
params.put("MiddleName", "D.");
params.put("LastName", "Doe");
params.put("BusinessPartnerCategory", "1");
final ODataUpdateRequest updateRequest =
ODataUpdateRequestBuilder
.withEntity("/sap/opu/odata/sap/API_BUSINESS_PARTNER", "A_BusinessPartner", keys)
.withBodyAsMap(params)
.build();
updateRequest.execute("DestinationName");
ODataDeleteRequestBuilder
Map<String, Object> keys = new HashMap<>();
keys.put("BusinessPartner", "12345");
keys.put("AddressID", "98765");
ODataDeleteRequest deleteRequest =
ODataDeleteRequestBuilder
.withEntity("/sap/opu/odata/sap/API_BUSINESS_PARTNER", "A_BusinessPartnerAddress", keys)
.build();
deleteRequest.execute("DestinationName");
I am trying to post data using Spring RestTemplate as below:
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
parameters.add("name1", "value1");
parameters.add("name2", "value2");
HttpMessageConverter<String> stringConverter = new StringHttpMessageConverter();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
List<HttpMessageConverter<?>> msgConverters = new ArrayList<HttpMessageConverter<?>>();
msgConverters.add(formConverter);
msgConverters.add(stringConverter);
restTemplate.setMessageConverters(msgConverters);
String xml = restTemplate.postForObject(myurl, parameters, String.class);
On the server part, I am using a simple servlet to handle request as follow:
String name1 = request.getParameter("name1");
The server returns the xml as String.
When I used HashMap instead of MultiValueMap without Converter, the parameters are null on the server side. But after using the above code, I am getting error
Cannot extract response: no Content-Type found
Can you plz provide me a simple example to achieve what I want.
Here is what I used to format data for the Spring POST:
//FormHttpMessageConverter
is used to construct form parameters to POST on the URI
HttpMessageConverter<?> formHttpMessageConverter = new FormHttpMessageConverter();
HttpMessageConverter<?> stringHttpMessageConverter = new StringHttpMessageConverter();
List<HttpMessageConverter> msgConverters = new ArrayList<HttpMessageConverter>();
msgConverters.add(formHttpMessageConverter);
msgConverters.add(stringHttpMessageConverter);
// Prepare acceptable media type
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
acceptableMediaTypes.add(MediaType.ALL);
// Prepare header
HttpHeaders headers = new HttpHeaders();
headers.setAccept(acceptableMediaTypes);
HttpEntity<MultiValueMap<String,String>> httpEntity = new HttpEntity<MultiValueMap<String,String>>(map,headers);
ResponseEntity<String> resp = restTemplate.exchange("https://risk.XXXX.XXXXXX.net",HttpMethod.POST,httpEntity,String.class);