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.
Related
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.
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);``
});}
I am trying to fetch parameters from angular JS $http service to rest service using **#queryParam** . I need to fetch lot of parameters(below have shown for 3 as an example ,but I need to use around 12-15 of them which I need to pass to the java side) ,so fetching all with #QueryParam makes the code look pretty bad .I am using GET.
How can I optimize this ?
Example what I am doing -
Angular Js code -
$http({
url: someUrl,
method: "GET",
params: {filter1: $scope.filter1,
filter2:$scope.filter2,
filter3:$scope.filter3
});
Java side -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(#QueryParam("filter1") final String filter1,
#QueryParam("filter2") final String filter2,
#QueryParam("filter3") final String filter3){
}
Also ,wanted to know the optimization in case when I am building URL instead of params object, and picking the same with #PathParam
$http.get('rest/test/getAllData/?filter1='$scope.filter1 +
'&filter2='$scope.filter2 + '&filter3='$scope.filter3 +
'&filter4='$scope.filter4)
I am able to do it by passing individually in #QueryParam . I am looking for optimized code when we a large number of parameters.
Create a POJO with all the required parameters.
In angular, do this
var obj = {};
obj.filter1 = $scope.filter1;
obj.filter2 = $scope.filter2;
obj.filter3 = $scope.filter3;
$http({
url: someUrl,
method: "GET",
params: obj
});
You can accept all the parameters in you rest like this -
#path("/getAllData")
#GET
#Produces({..}
public response getAllData(MyPojo obj){
//String filter1 = obj.filter1;
}
You can do it in 2 ways:
1) org.json.simple.JSONObject.
2) Bean or POJO Class.
AngularJS Controller:
var URL = appURL+'/adm/addCollProcess.do';
var json = {"col_pro_id":$scope.col_pro_id, "col_code": $scope.col_code, "exam_type_ids": $scope.exam_types.toString().replace("[","").replace("]",""),
"created_by" : "admin", "file_path" : $scope.file_path, "website" : $scope.website, "facebook" : $scope.facebook};
// using JSONObject
$http.post(URL, json).then(function(response){
if(response.data){
// Code
}
});
// using Bean Class
$http.post(URL, JSON.stringify(json)).then(function(response){
if(response.data){
// Code
}
});
Java Controller:
// using JSONObject
#RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public boolean addCollProcess(#RequestBody JSONObject json){
// Code
}
// using Bean Class:
#RequestMapping(value="/addCollProcess.do", method=RequestMethod.POST)
public #ResponseBody boolean addCollProcess(#RequestBody AdmissionProcessBean processBean) {
// Code
}
After a while I got the first part of the Google Channel API working. Now I have some problems with sending a message from the JavaScript client to the server.
Here is the servlet for the Google Channel API connection:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user != null) {
ChannelService channelService = ChannelServiceFactory.getChannelService();
String token = channelService.createChannel(user.getUserId());
FileReader reader = new FileReader("index.html");
CharBuffer buffer = CharBuffer.allocate(16384);
reader.read(buffer);
reader.close();
String index = new String(buffer.array());
index = index.replaceAll("\\{\\{ token \\}\\}", token);
resp.setContentType("text/html");
resp.getWriter().write(index);
} else {
resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
}
The index.html looks like following:
<script src="/_ah/channel/jsapi"></script>
<body>
<script type="text/javascript">
onOpened = function() {
alert("opened");
}
var token = "{{ token }}";
var channel = new goog.appengine.Channel(token);
var handler = {
'onopen' : onOpened,
'onmessage' : onMessage,
'onerror' : function() {
},
'onclose' : function() {
}
};
var socket = channel.open(handler);
socket.onopen = onOpened;
socket.onmessage = onMessage;
function sendMessage() {
// Send JSON object to server
}
</script>
<h1>Google Test Channel API</h1>
<form>
<input type="button" value="Send" onclick="sendMessage();">
</form>
</body>
If I load the application I get the opened alert, I believe the connection is working. Now I would like to send a message to the server, if someone clicks on the button.
I read that I have to use the XMLHttpRequest function with POST or GET. But I won’t pass a new url, I
would just pass a value. Is there a way to send a JSON object to the server?
Something like:
{
"message": "This is a JavaClient message!"
}
This doesn't really have much to do with the Chanel API - it's just a standard xhr call back to the server. You can use standard code like this, or use a library such as jquery like this.
If you need to parse javascript into JSON use JSON.stringify().
At the server you can process your request as required, send a response back to the client via standard HTTP or use the Chanel API to send a message not just to the original client, but to all connected clients.
Are you familiair with the channel API blog post of Nick Johnson:
http://blog.notdot.net/2011/07/Using-the-Channel-API-on-App-Engine-for-instant-traffic-analysis
App Engine's Channel API is pretty much only for sending messages from the server->client. It's a one way channel.
That's fine because it's not hard to build the client->server channel, but you do have to build it yourself, it's not for free. You do have to define your own url for the client->server message, then use an XMLHttpRequest to send your message to that url.
There's a small exception in that the Channel API also has a built on mechanism to notify the server of connects/disconnects. Under the cover, these are done using XMLHttpRequests to predefined urls (I think it's something like _ah/channel/disconnect or something. These won't be useful to you since they're automatically called - you can't define when they are called, or the content.
So yeah, just implement your own URL handler, and send your JSON data to that URL.
I'm trying to a write simple REST Java web-service. I use Provider interface on the server side and Dispatch on the clients. I'm trying to transmit a value in header of POST request but there is some problem.
My client code:
private void invoke(Dispatch<Source> dispatch
Object data) {
Map<String, Object> request_context = dispatch.getRequestContext();
request_context.put(MessageContext.HTTP_REQUEST_METHOD, "POST");
request_context.put("org.kpi.asd", "SOME TEXT");
StreamSource source = make_stream_source(data.toString());
dispatch.invoke(source);
}
My server code:
public Source invoke(Source request) {
// Filter on the HTTP request verb
if (ws_ctx == null) throw new RuntimeException("DI failed on ws_ctx.");
// Grab the message context and extract the request verb.
MessageContext msg_ctx = ws_ctx.getMessageContext();
String aaa = (String) msg_ctx.get("org.kpi.asd");
}
On server: aaa is null. I can't understand why. Help me, please (:
the message context is not where you set arbitrary http headers. there is another property in the message context which contains the http headers, see HTTP_REQUEST_HEADERS.