I send async requests to facebook. Each of those requests has field "notofication uri".
When async jobs are all done, this URI will be used to notify the caller with POST action and the id of the object.
I've wrote spring action in controller to obtain that id:
#RequestMapping(value = "/callback", method = RequestMethod.POST
public void asyncRequestSet(#RequestBody String body,
#RequestParam("offer_id") Long offerId,
#RequestParam("user_id") Long userId) {
logger.info("{}", body);
}
Example callback url: http://example.com/callback?user_id=1&offer_id=1
But the body of request is:
--------------------------9c15923bd5bc01ce
Content-Disposition: form-data; name="async_request_set_id"
5011222203926
--------------------------9c15923bd5bc01ce--
How could I get id "5011222203926" without using regex.
Related
I have a scenario where http POST request execute, call another get request and return response of get request. Here is my code
public class EmployeeController : ControllerBase
{
private readonly IBusControl _bus;
public EmployeeController(IBusControl bus)
{
_bus = bus;
}
[HttpPost]
public async Task<IActionResult> Emp(EmployeeModel employee)
{
Uri uri = new Uri("rabbitmq://localhost/ret_eligibility");
var endPoint = await _bus.GetSendEndpoint(uri);
await endPoint.Send(employee);
return Ok("Success");
}
[HttpGet]
[Route("getRetFund")]
public IActionResult fund()
{
Fund fund = RetFundConsumer.fund;
return Ok(fund.retfund);
}
}
I want to call getRetFund request in POST request method, So that when employee data is sent to queue using postman, it call second service which consume message and send response back. This response will be shown then in console.
I also have tried the following POST method.
[HttpPost]
public async Task<IActionResult> Emp(EmployeeModel employee)
{
Uri uri = new Uri("rabbitmq://localhost/ret_eligibility");
var endPoint = await _bus.GetSendEndpoint(uri);
await endPoint.Send(employee);
//return Ok("Success");
Fund fund = RetFundConsumer.fund;
return Ok("your retirement fund is " + fund.retfund);
}
But this throw null Exception as it call second service before executing POST request. The response would be greatly appreciated.
This would never work. You need to spend time about both Web API request handling scope and MassTransit message handling scope.
In short, both Web API and MassTransit message handling is scoped to one message. There is no way you can consume a response message, somehow magically keeping the HTTP session open. The consumer gets disposed when it finishes handling a message.
You can do it, though, but you need to use the MassTransit request/response feature.
public class EmployeeController : ControllerBase
{
private readonly IRequestClient<EmployeeModel> _client;
public EmployeeController(IClientFactory clientFactory)
=> _client = clientFactory.CreateRequestClient<EmployeeModel>(
new Uri("rabbitmq://localhost/ret_eligibility"));
[HttpPost]
public async Task<IActionResult> Emp(EmployeeModel employee)
{
var response = await _client.GetResponse<Fund>(employee);
return Ok("your retirement fund is " + fund.retfund);
}
}
Of course, you need to change your consumer accordingly to send a message back. Check the documentation referenced above for the details.
I have a following situation which I have never seen before. I am using code below to declare a Post action.
[HttpPost]
[Route("")]
public async Task<HttpResponseMessage> Insert(InsertRequest request)
{
var body = await Request.Content.ReadAsStringAsync();
}
Now, when I am sending request to this endpoint using Postman with Content-Type = Application/Json I get some value for request and empty string for body.
If I do PostAsJsonAsync with HttpClient to this endpoint I will get null for request and request content for body.
How is that possible?
To support POST you need to add attribute [FromBody] to the request parameter.
[HttpPost]
[Route("")]
public async Task<HttpResponseMessage> Insert([FromBody] InsertRequest request)
{
var body = await Request.Content.ReadAsStringAsync();
}
I am trying to create a request using retrofit with a key-value (& separated) payload and simple user authentication, as it can be done in the following curl command:
curl -X POST -d "grant_type=refresh_token&refresh_token=<refresh_token>" -u"<client_id>:<client_secret>" http://localhost:8000/o/token/
How can I create a request in retrofit that supplies the above data? I need both the interface method and the creation of RequestBody if it used.
UPDATE:
I used the following code
interface method definition:
#POST("/o/token/")
Observable<ServerToken> refreshAccessToken(#Header("Authorization") String auth, #Body RequestBody tokens);
calling the implementation:
RequestBody body = new FormEncodingBuilder()
.add("grant_type", "refresh_token")
.add("refresh_token", serverToken.refresh_token)
.build();
String auth = Credentials.basic("<client_id>", "<client_secret>");
mTokenApi.refreshAccessToken(auth, body)
But I am getting a Content-Type: application/json in the request and an empty request body.
How can I fix this?
The correct way to do it is:
interface method definition:
#FormUrlEncoded
#POST("/o/token/")
Observable<ServerToken> refreshAccessToken(#Header("Authorization") String auth,
#Field("grant_type") String grantType,
#Field("refresh_token") String refreshToken);
calling the implementation:
String auth = Credentials.basic(clientID, clientSecret);
mTokenApi.refreshAccessToken(auth, "refresh_token", serverToken.refresh_token)
The HttpClient custom Client Message Handlers insert themselves in the client-side pipeline when making web api calls. This info is from this article
The author says that these message handlers go into action as the request is being sent out and also when the response is received back from the server.
I understand these client message handler's role as request is being sent out from client to the Server because the sendAsync method provides the request object. One can add custom request headers, etc.
I do not understand the usefulness of these message handlers AFTER the response is received from the server because the sendAsync method does not provide access to the response object. So, I am not sure how these client side message handlers are useful on the return journey of the request.
I am obviously missing something here.
Actually you do get access to the response message inside the message handler. For example, in the following handler, I am logging outgoing request and incoming response. Now as long as I use this instance of HttpClient, all calls made through it write traces of requests and response.
HttpClient client = new HttpClient(new LoggingHandler(new HttpClientHandler()));
public class LoggingHandler : DelegatingHandler
{
public LoggingHandler(HttpMessageHandler innerHandler)
: base(innerHandler)
{
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Console.WriteLine("Request:");
Console.WriteLine(request.ToString());
if (request.Content != null)
{
Console.WriteLine(await request.Content.ReadAsStringAsync());
}
Console.WriteLine();
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
Console.WriteLine("Response:");
Console.WriteLine(response.ToString());
if (response.Content != null)
{
Console.WriteLine(await response.Content.ReadAsStringAsync());
}
Console.WriteLine();
return response;
}
}
In my js file, i have an Ext.Ajax.request to remove a user from a table. The most important thing is to send the username. This is my request code:
Ext.Ajax.request({
url: 'deleteUser.html',
method: 'POST',
headers: {'Content-Type': 'text/html'},
waitTitle: 'Connecting',
waitMsg: 'Sending data...',
params: {
username:username
},
scope:this,
success: received,
failure: function(){console.log('failure');}
});
In the firebug i can see the post myapp/admin/deleteUser.html. In the post tab appears username=example.
In the server-side i have a controller which catchs the post:
#RequestMapping(method=RequestMethod.POST, value="/deleteUser")
public #ResponseBody Map<String,String> deleteUserHandler(#RequestParam("username")String username, Model model){
userService.deleteUser(username);
Map<String,String> responseMap = new HashMap<String, String>();
responseMap.put("message", "Success");
return responseMap;
}
if i have #RequestParam("username") i receive a 400 error (Incorrect request) and if i try another ways to get params i get null.
Could anybody help me please?
In the firebug i can see the post myapp/admin/deleteRole.html.
In the post tab appears username=example.
you say you can see web calling deleteRole.html.
But in your ajax and your Controller it should be call "/deleteUser"
How if you log something in your controller so we can determine if that function have been called.
First try connection between your html mapped to your function correctly
#RequestMapping(method=RequestMethod.POST, value="/deleteUser")
public #ResponseBody String deleteUserHandler(#RequestParam("username") String username){
System.out.println("deleteUserHandler called");
return "{\"message\" : \"success\"}";
}
If your function called it should be ok..