How to send request with Spring mvc? - spring

I'm learning how to make telegram bots. With webhook telegram send you a post request with some message.
I want my server to get this request, process and send new request to telegram get/post.
For example:
telegram bot sent me a post request with a new message in chat.
i get this request and proccess it.
now i need to send new get request to telegram to post a message like https://api.telegram.org/bot/sendMessage?chat_id=&text=hello
Is there a way to send request directly from controller? I know that i can redirect request, but redirect can be only GET and i need completly new request.

You can either use Spring's RestTemplate:
RestTemplate restTemplate = new RestTemplate();
UriComponentsBuilder telegramRequestBuilder = UriComponentsBuilder.fromHttpUrl("https://api.telegram.org/bot/sendMessage")
.queryParam("chat_id", 1)
.queryParam("text", "Hello");
ResponseEntity<String> response
= restTemplate.getForEntity(telegramRequestBuilder.toUriString(), String.class); // or to a Java pojo class
Or use the newer Spring WebClient for this. See this link for example.

you can use Rest Template to send request to a web service.this is a spring guide on how to do it.

Related

Multiple #RequestBody in feign client exception when executing service

I am giving call from User microservice to Account microservice via feign client. I am passing 3 request body in method call. I am getting exception when I am executing user service stating that multiple request body is present in feign call.
#PostMapping("/create)
ResponseEntity<Long> createAccount(#RequestBody List<UserInfo> userInfo, #RequestBody List<AddressInfo> addressInfo, #RequestBody List<OrderInfo> orderInfo);
Is there a limit on number of request body I can send via feign? I just don't want to club all three list under one object and want to send them separately.
Can any one please help me with this?
You can't pass multiple Body in HTTP request (see docs). Does your Account microservice really have API that require more than one body?

How to send request data in post request using zuul filter

I am new to Zuul and I want to redirect to external url using zuul pre filter in spring boot application. I want to send request data to call external url (post method api in python).
When i try to send request data using below code, when i hit the url from postman,i get 405 The method is not allowed for the requested URL.
my code:
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
InputStream in = request.getInputStream();
String body = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
ctx.set(body);
when i hit the url like http://localhost:8080/customers/ passing request body in postman,it should redirect to external url (api method) by sending post data but i am getting getting 405 The method is not allowed for the requested URL.
Could any one please help me in solving this issue? I want to send request data in zuul and call external api. Thank you

Spring boot Webclient's retrieve vs exchange

I have started using WebClient in my Spring boot project recently.
Can somebody throw some light on the differences/usages between exchange and retrieve method in WebClient.
I undertand that exchange returns Mono<ClientResponse> and retrieve returns ResponseSpec, I just want to know when/why I should use each one of them.
Much Thanks.
Adding to #JArgente's answer.
According to the official documentation of the retrieve() method:
Perform the HTTP request and retrieve the response body.
...
This method is a shortcut to using exchange() and decoding the response body through
ClientResponse.
and the exchange() method
Perform the HTTP request and return a ClientResponse with the response status and headers. You can then use methods of the response to consume the body:
The retrieve() method decodes the ClientResponse object and hands you the ready-made object for your use. It doesn't have a very nice api for handling exceptions.
However on the other hand the exchange() method hands you the ClientResponse object itself along with the response status and headers. With exchange method you get fine grained control over your response objects and a better way to handle the response object and the exceptions.
If you just want to consume some api go with retrieve().
If you want a better control over your response objects, headers and exceptions, go with exchange().
Update 1
Starting from Spring 5.3, the exchange() method is deprecated due to possible memory/connection leaks. exchangeToMono() or exchangeToFlux() can be used instead.
Thanks #rhubarb for the update.
According to spring Webclient api documentation the difference between the two is that exchange retrieve in addition to the body other http response information like headers and status, while retrieve only returns body information.
So If you only need the body information you should use retrieve, because it is a shortcut for exchange and then get the body, but if you need other information like http status you must use exchange.

RestTemplate postForObject return HttpClientErrorException: 401 null

I am trying to send a post message to authentication server and I am usign postforobject. When I run the program, i am getting "Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 401 null" error
RestTemplate rest = new RestTemplate();
String responseEntity;
String uri = "http://...";
responseEntity = rest.postForObject(uri, null, String.class);
System.out.println(responseEntity);
Also I tried
responseEntity = rest.postForObject(uri, "", String.class);
Same result, it didn't work.
When I using Simple Rest Client it works
enter image description here
Any idea?
401 null probably means that the server expected some form of authentication but none was presented (i.e. no Authorization header in your request)
The most likely explanation is: the Simple REST Client (re)uses Chrome's cookies. If you previously authenticated against your service using a form login, the Simple Rest Client will reuse the JSESSIONID cookie. To detect that simply press F12 and open the network tab of your debugger. FYI there are other browser plugins, for example "Advanced REST Client", which give you more visibility over what's being sent to the server.
When you send a request using restTemplate, it doesn't have access to the session cookie (which is to be expected). You should either post to URI that allows anonymous access, or provide some form of authentication in the request. If you require additional help please post your security configuration.

Cannot put parameters in body for OAuth2 POST requests in a REST service

It seems I am missing something very basic here.
I made a REST Api that takes POST requests for generating tokens using the Apache Oltu OAuth2 service, that looks something like this :
#POST
#Consumes("application/x-www-form-urlencoded")
#Produces("application/json")
public Response authorize(#Context HttpServletRequest request) throws OAuthSystemException, IOException {
try {
OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
When I use HttpRequester or Postman to test the service, it works perfectly fine on condition that I input all authentication and OAuth2 parameters as input parameters, as an example :
https://localhost:8443/rest/OAuthService/token?grant_type=password&username=userfortest&password=Johhny1é&client_id=1234
However I read, that for any POST requests, all parameters should be
in the Body of the HTTP request and never sent through with the url as a simple parameter. When I try to pass it in the body of the HTTP request, so as to make the request secure (so the url is the same without parameters and all params are specified in the body), it seems like it doesn't receive anything from the body as it throws an exception, after
OAuthTokenRequest oauthRequest = new OAuthTokenRequest(request);
with the following message :
{"error_description":"Missing grant_type parameter value","error":"invalid_request"}
Is it the intended behaviour of Oltu/OAuth2 for the parameters to be passed through with the url? Or what am I doing wrong?
Thanks in advance.
Your answer is here: Unable to retrive post data using ,#Context HttpServletRequest when passed to OAuthTokenRequest using Oltu
I did exactly what he said and it worked perfectly.
You need modify Response authorize() parameters.

Resources