how to send data from servlet to rest api - java

I want to send data from my servlet to a rest api .
Is it how it's done :
protected void doPost(
HttpServletRequest request
, HttpServletResponse response
) throws ServletException, IOException {
String Id= "MyId";
response.setContentType("application/json");
response.getWriter().write(Id);
getServletContext()
.getRequestDispatcher("<PathofAPI>")
.forward(request, response);
}
And once the data is send how to retreive it in my rest api

Alternatively you must create POJO class for you Id parameter with getters and setters:
String createRequestUrl="YOUR_LINK WHERE_YOU GET answer FROM";
RestTemplate template=new RestTemplate();
your_POJO_object.setYour_Pojo_Object(Id);
ObjectMapper objectMapper = new ObjectMapper();
MultiValueMap<String, String> orderRequestHeaders=new
LinkedMultiValueMap<String,String>();
orderRequestHeaders.add("Content-Type", "application/json");
orderRequestHeaders.add("Accept", "application/json");
String orderCreateRequest=objectMapper.writeValueAsString(YOUR POJO object.class);
HttpEntity<String> orderRequest=new HttpEntity<String>(orderCreateRequest, orderRequestHeaders);
String response=template.postForObject(createRequestUrl, orderRequest, String.class);

What you want to acheive is a bit unclear to me.
By writing "MyId" to the response before letting "PathofServet" process the request, you're breaking the json format in the response.
Have you an exemple of what the servlet "PathofServlet", expects as request and send as response ? And what you would like your servlet to response ?

Related

Xml tags printing differently in Restcontroller

I am using a controller for post mapping in spring
#PostMapping(value ="/HttpNoRespAdapter",consumes = { MediaType.APPLICATION_FORM_URLENCODED_VALUE, MediaType.APPLICATION_XML_VALUE}, produces=MediaType.APPLICATION_XML_VALUE)
protected String process(#RequestBody String request, HttpServletResponse response) {
}
I am taking whatever coming in the requestbody as string, the following xml should come
<REQ><FEATURE>DELIVERY-RECEIPT</FEATURE><TIME-STAMP><![CDATA[20200925190730]]></TIME-STAMP><TRANSACTION-ID><![CDATA[71554]]></TRANSACTION-ID><SMPP-ID><![CDATA[airtel]]></SMPP-ID><COMMAND-ID><![CDATA[5]]></COMMAND-ID><OA><![CDATA[8407600010]]></OA><DA><![CDATA[555]]></DA><DCS><![CDATA[0]]></DCS><SMS><![CDATA[stat:DELIVRD err:000 Text:silent]]></SMS><MESSAGE-ID><![CDATA[19]]></MESSAGE-ID></REQ>
But it coming as
%3CREQ%3E%3CFEATURE%3EDELIVERY-RECEIPT%3C%2FFEATURE%3E%3CTIME-STAMP%3E%3C%21%5BCDATA%5B20201007175019%5D%5D%3E%3C%2FTIME-STAMP%3E%3CTRANSACTION-ID%3E%3C%21%5BCDATA%5B60564%5D%5D%3E%3C%2FTRANSACTION-ID%3E%3CSMPP-ID%3E%3C%21%5BCDATA%5Bairtel%5D%5D%3E%3C%2FSMPP-ID%3E%3CCOMMAND-ID%3E%3C%21%5BCDATA%5B5%5D%5D%3E%3C%2FCOMMAND-ID%3E%3COA%3E%3C%21%5BCDATA%5B8007600010%5D%5D%3E%3C%2FOA%3E%3CDA%3E%3C%21%5BCDATA%5B555%5D%5D%3E%3C%2FDA%3E%3CDCS%3E%3C%21%5BCDATA%5B0%5D%5D%3E%3C%2FDCS%3E%3CSMS%3E%3C%21%5BCDATA%5Bid%3A69+sub%3A001+dlvrd%3A001+submit+date%3A2010071750+done+date%3A2010071750+stat%3ADELIVRD+err%3A000+Text%3Asilent%5D%5D%3E%3C%2FSMS%3E%3CMESSAGE-ID%3E%3C%21%5BCDATA%5B69%5D%5D%3E%3C%2FMESSAGE-ID%3E%3C%2FREQ%3E=
the xmltags are been replaced wrongly. how can i rectify this??
Try to use java.net.URLDecoder:
request = URLDecoder.decode(request, "UTF-8");

Generics with Spring RESTTemplate for a POST call

My question is similar to below question,
Generics with Spring RESTTemplate
The above solution is for a GET call, but am looking for a POST call and in my case input payload is also a wrapper object with generic.
This is how my controller function looks like:
ResponseWrapper<ResponseModel> apiForPost(
#RequestBody RequestWrapper<RequestModel> inputPayload,
#Context HttpHeaders headers) {
}
This is the sample code am trying and where am facing the issue
RequestWrapper<RequestModel> request = new RequestWrapper<>();
//code to set above request object
String url ="http://some_url";
RestTemplate restTemplate = new RestTemplate();
ResponseWrapper<ResponseModel> response = restTemplate.exchange(url,
HttpMethod.POST,
request,
new ParameterizedTypeReference<ResponseWrapper<ResponseModel>>() {}).getBody(); // shows error at that the 3rd parameter (request) cannot be of that type
As per the documentation this is what exchane method expects:
exchange(URI url, HttpMethod method, HttpEntity requestEntity, ParameterizedTypeReference responseType)
(https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html)
If anyone can help me on this, that would be great. Thanks.

How do you get a converted request from RestTemplate after a GET/POST/PUT call?

I have no issues using Spring's RestTemplate to make POST or GET calls to an endpoint. I've also set the message converter as JSON (MappingJacksonHttpMessageConverter), no prob.
My question is, how can I grab the converted request I'm sending?
Example, if I do this:
ResponseEntity<T> result = this.restTemplate.postForEntity("http://{endpoint_url...}", dtoEntryObj, SomeDTO.class);
How could I grab the JSON that it's sending to the endpoint?
RestTemplate can send formats other than json as well. To get the actual body of the request, you will need to implement your own ClientHttpRequestInterceptor and use RestTemplate#setInterceptors() to register it.
Something like
RestTemplate template = new RestTemplate();
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {
#Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body,
ClientHttpRequestExecution execution) throws IOException {
// you have access to the body
// do something with it
return execution.execute(request, body);
}
};
template.setInterceptors(Arrays.asList(interceptor));
Note that with json, RestTemplate uses a MappingJackson2MessageConverter which internally uses an ObjectMapper. You can simulate it if the above solution doesn't work for you.

Return from doPost() in JSP

I am trying to implement REST type architecture without using any framework. So I am basically calling a JSP from my client end which is doing a doPost() on to the remote server providing services. Now I am able to pass the data from client to server in JSON format but I don know how to read the response. Can someone help me out with this.
Client Side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
....
....
HttpPost httpPost = new HttpPost("http://localhost:8080/test/Login");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//Send post it as a "json_message" paramter.
postParameters.add(new BasicNameValuePair("json_message", jsonStringUserLogin));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse fidresponse = client.execute(httpPost);
....
....
}
Server Side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsonStringUserLogin = (String)request.getParameter("json_message");
....
....
request.setAttribute("LoginResponse", "hello");
// Here I need to send some string back to the servlet which called. I am assuming
// that multiple clients will be calling this service and do not want to use
// RequestDispatcher as I need to specify the path of the servlet.
// I am looking for more like return method which I can access through
// "HttpResponse" object in the client.
}
I just started with servlets and wanted to implement a REST service by myself. If you have any other suggestion please do share... Thank You,
in doPost you simply have to do :
response.setContentType("application/json; charset=UTF-8;");
out.println("{\"key\": \"value\"}"); // json type format {"key":"value"}
and this will return json data to client or servlet..
reading returned data using jquery ajax ...
on client side using jquery do the following :
$.getJSON("your servlet address", function(data) {
var items = [];
var keys= [];
$.each(data, function(key, val) {
keys.push(key);
items.push(val);
});
alert(keys[0]+" : "+items[0]);
});
on servlet you know how to read json data
After you executed the post you can ready the response like this.
HttpEntity entity = fidresponse.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String l = null;
String rest = "";
while ((l=br.readLine())!=null) {
rest=rest+l;
}
Here rest will contain your json response string.
You can also use StringBuffer.

How do I read the response header from RestTemplate?

I am posting information to a web service using RestTemplate.postForObject. Besides the result string I need the information in the response header. Is there any way to get this?
RestTemplate template = new RestTemplate();
String result = template.postForObject(url, request, String.class);
Ok, I finally figured it out. The exchange method is exactly what i need. It returns an HttpEntity which contains the full headers.
RestTemplate template = new RestTemplate();
HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class);
String resultString = response.getBody();
HttpHeaders headers = response.getHeaders();
Best thing to do whould be to use the execute method and pass in a ResponseExtractor which will have access to the headers.
private static class StringFromHeadersExtractor implements ResponseExtractor<String> {
public String extractData(ClientHttpResponse response) throws
{
return doSomthingWithHeader(response.getHeaders());
}
}
Another option (less clean) is to extend RestTemplate and override the call to doExecute and add any special header handling logic there.
HttpEntity<?> entity = new HttpEntity<>( postObject, headers ); // for request
HttpEntity<String> response = template.exchange(url, HttpMethod.POST, entity, String.class);
String result= response.getBody();
HttpHeaders headers = response.getHeaders();
I don't know if this is the recommended method, but it looks like you could extract information from the response headers if you configure the template to use a custom HttpMessageConverter.

Categories

Resources