vertx get body of a simple post reques - java

Their doc on vertx website isn't quite clear on how to receive the body of a request.
var vertx = Vertx.vertx();
var server = vertx.createHttpServer();
var Router = require("vertx-web-js/router");
var BodyHandler = require("vertx-web-js/body_handler");
var router = Router.router(vertx);
router.route().handler(BodyHandler.create().handle);
router.route('POST', "/a").handler(function (routingContext) {
var response = routingContext.response();
response.setChunked(true);
response.write("a json received");
var str = routingContext.getBodyAsJson()
console.log(str);
// Now end the response
routingContext.response().end();
});
I get the error:
vertx-js/util/console.js:9 ReferenceError: "inspect" is not defined
How am I supposed to know what to call if they don't even put it in their doc..

Paulo said my version of vertx was outdated and this was a bug. I'll take his word for it. In the meantime I tried doing it in Java like in the answer I got. However I had more success doing it like this:
router.route().handler(BodyHandler.create());
router.route(HttpMethod.POST, "/iamonline").handler(rc -> {
JsonObject json = rc.getBodyAsJson();
System.out.println(json.getString("id"));
HttpServerResponse response = rc.response();
response.putHeader("content-type", "application/json");
// Write to the response and end it
response.end("{\"status\": 200}");
});

I ran into the same the first time. Use the .bodyHandler which is a convenience method for receiving the entire request body in one piece.
As a reference, I'll give you an example in Java (you can easily "transform" it into ECMAScript):
public void login(final RoutingContext routingContext) {
routingContext.request().bodyHandler(bodyHandler -> {
final JsonObject body = bodyHandler.toJsonObject();
// `body` now contains you what you POST'ed
});
}

Related

Unable to send params in servlet

I have angular code
app.controller('add', function ($scope, $http) {
$scope.add = function() {
$scope.msg = "no connect";
var data = {name:'soso',description:'buba',method:'POST'};
$http.post(host + "/add-component",data)
.then(function (response) {
$scope.msg = response.data;
});
}
});
in my servlet, I want to catch it
resp.setContentType("application/json; charset = utf8");
String name = req.getParameter("name");
String description = req.getParameter("description");
but my name and description both = null;
You are sending data as POST request body, not request parameters. This is documented in the angular docs for post method:
url string
Relative or absolute URL specifying the destination of the request
data *
Request content
Take a look at this answer to see how to read request body.
These days it's easier to use Spring Boot or other frameworks to handle your server side endpoints. There is nothing wrong with using Servlets but you will have to write more code yourself.

Play framework 2.6 - Java : Ws request POST with oAuth Instagram

I'm trying to communicate with Instagram's API but the reply I get back from my request says that the parameters I passed onto the body weren't detected.
{"error_type":"OAuthException","code":400,"error_message":"You must provide a client_id"}
I tried to send the request by passing a JsonNode or a string inside .post(), like below, but both where unsuccessful.
public CompletionStage<Result> getInstagramToken() {
String code = request().getQueryString("code");
if(code != null) {
WSRequest request = ws.url("https://api.instagram.com/oauth/access_token").setContentType("application/x-wwww-form-urlencoded");
// Json body
/*JsonNode body = Json.newObject()
.put("client_id", insta_clientId)
.put("client_secret", insta_clientSecret)
.put("grant_type", "authorization_code")
.put("redirect_uri", redirect_uri)
.put("code", code);*/
// String body
String body = "client_id="+insta_clientId+"&client_secret="+insta_clientSecret+"&grant_type=authorization_code&redirect_uri="+redirect_uri+"&code="+code;
CompletionStage<WSResponse> response = request.post(body);
return response.thenApplyAsync(resp -> ok(resp.asJson()), exec);
}
return null;
}
The same request passed flawlessly when trying to send it by using a curl command on a terminal or with the Rested plugin on chrome ( where "content type" is set to "application/x-www-form-urlencoded" and the parameters are placed inside "Request body" )
Does anyone have any idea as to how I am supposed to send this request ?
ps: I am also looking for a way to retrieve the value received from my request and store it in a variable instead of returning it to the client.
It seems you are missing a:
.setContentType("application/x-www-form-urlencoded")
Look at our code below. In the post() you can also use a Json object so you can send a HashMap:
CompletionStage<Result> out = ws.url(cbUrl)
.setAuth(<<your user>> , <<your password>>, WSAuthScheme.BASIC)
.setRequestTimeout(Duration.ofSeconds(5))
.setContentType("application/x-www-form-urlencoded")
.post("param=value")
.handle((response, error) -> {
// Was the Chargebee API successful?
if (error == null) {
// Debugging purposes
JsonNode jn = response.asJson();
Logger.debug(Json.toJson(postMap).toString());
Logger.debug(jn.toString());
// Success stuff
return ok("good");
} else {
// Error stuff
return ok("bad");
}
});
Hope this helps you.

Calling Node.Js Rest API(POST) from Java Spring MVC

How to integrate node.js and java micro services. I'm able to call node rest api from java spring mvc but not able to post data to node api. Getting empty body in request object at node project.
FYI: Node.js(express) -REST api(POST method)
Spring MVC -REST -api(POST method)
Java:
String url = "localhost:3010/upload";
JSONObject jsonob1=new JSONObject(); jsonob1.put("upfile", file);
jsonob1.put("ty", "ACT");
HashMap<String, String> header = getHeaderValues(uploadreq.getAuthToken(), "action");
status = getHttpClient.executePostRequest(url,jsonob1,header);
LOGGER.debug("result {}", status);
NodeJs:
var express = require("express");
var router = express.Router();
router.post('/upload', function (req, res) { console.log(req); });
Please ignore it, its resolved by myself, Access req.body at nodejs side as following
var qs = require('querystring');if(req.method=='POST') {
var body='';
req.on('data', function (data) {
body +=data;
});
req.on('end',function(){
var POST = qs.parse(body);
console.log(POST);``
});}

get source of URL didn't work correctly [duplicate]

I wish to automatically uncompress GZiped response.
I am using the following snippet:
mywebclient.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
mywebclient.Encoding = Encoding.UTF8;
try
{
var resp = mywebclient.DownloadData(someUrl);
}
I have checked HttpRequestHeader enum, and there is no option to do this via the Headers
How can I automatically decompress the resp? or Is there another function I should use instead of mywebclient.DownloadData ?
WebClient uses HttpWebRequest under the covers. And HttpWebRequest supports gzip/deflate decompression. See HttpWebRequest AutomaticDecompression property
However, WebClient class does not expose this property directly. So you will have to derive from it to set the property on the underlying HttpWebRequest.
class MyWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return request;
}
}
Depending on your situation, it may be simpler to do the decompression yourself.
using System.IO.Compression;
using System.Net;
try
{
var client = new WebClient();
client.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
var responseStream = new GZipStream(client.OpenRead(myUrl), CompressionMode.Decompress);
var reader = new StreamReader(responseStream);
var textResponse = reader.ReadToEnd();
// do stuff
}
I created all the temporary variables for clarity. This can all be flattened to only client and textResponse.
Or, if simplicity is the goal, you could even do this using ServiceStack.Text by Demis Bellot:
using ServiceStack.Text;
var resp = "some url".GetJsonFromUrl();
(There are other .Get*FromUrl extension methods)

use java variable inside ajax call

I have a periodically calling Ajax call. I use this ajax call to invoke an endpoint. Below I have mentioned my jsp file(polling.jsp). The service has hosted in tomcat server. Expected output from the variable title is "Metallica". But I get below error in firebug without getting the alert.
ReferenceError: Metallica is not defined
alert(Metallica);
I need to check weather the web service is calling time to time as I defined. If I did not put the alert ,
alert(<%=name%>);
then I can see ajax call is working properly in firebug. But I need to put the alert their to get the response form the web service.
polling.jsp
<script>
<%
Client client = Client.create();
%>
var set_delay = 5000,
callout = function () {
$.ajax({
})
.done(function (response) {
<%
WebResource webResource = client
.resource("http://localhost:8080/RESTfulExample/rest/json/metallica/get");
ClientResponse response1 = webResource.accept("application/json")
.get(ClientResponse.class);
if (response1.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response1.getStatus());
}
String output = response1.getEntity(String.class);
Gson gson = new Gson();
Track track=gson.fromJson(output,Track.class);
String name=track.getName().toString();
%>
alert(<%=name%>);
})
.always(function () {
setTimeout(callout, set_delay);
});
};
callout();
</script>
Any help is greatly appreciated. Thanks.
Try wrapping up in double quotes
alert("<%=name%>");
Since <%=name%> will be replaced by value say StackOverflow so you are actually doing
alert(StackOverflow);// will not work as StackOverflow is not an Object/Variable
Hence you need to do alert("StackOverflow");

Categories