When I'm trying to send some json to my node.js server req.body is empty and I have no idea why. The headers I'm sending are received.
This is the java code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(json, "UTF8");
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("test", "test");
HttpResponse httpResponse = httpClient.execute(httpPost);
And this is the node.js code:
exports.checkMail = function(req, res) {
var user = req.body;
var header = req.headers;
var email = user.email;
db.collection('users', function(err, collection) {
collection.findOne({'email':email}, function(err, item) {
if (item) {
res.send({'error':0, 'message':'email available'});
} else {
res.send({'error':4, 'message':'email already taken'});
}
});
});
};
Any ideas of what I might be missing?
EDIT:
Sorry forgot to mention. I'm using Express.
And the json i'm sending is:
{"email":"email#email.com"}
What I get from req.body is just: {}
EDIT2:
app.js
var express = require('express'),
post = require('./routes/posts'),
user = require('./routes/user');
var app = express();
app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
//app.use(express.json());
//app.use(express.urlencoded());
});
app.get('/auth', user.login);
app.post('/auth', user.addUser);
app.put('/auth/:id', user.updateUser);
app.post('/checkmail', user.checkMail);
app.post('/reset', user.resetPassword);
app.listen(8080);
console.log('Listening on port 8080...');
Probably too late to answer, but if anybody has this same problem this is what worked for me:
//It is important that if we are sending a Content-Type application/json, the entity has to receive a json
JSONObject js = new JSONObject();
js.put("key", value);
String url = "http://mylocalhosturl";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(js.toString(), HTTP.UTF_8);
//Setting the content type is very important
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
//Execute and get the response.
HttpResponse response = httpClient.execute(httpPost);
Hope this helps to someone.
You app.js file should have these middleares included;
var express = require('express');
var app = express();
// app configs; include these;
app.use(express.json());
app.use(express.urlencoded());
// other configurations
app.use(app.router)
// ...
Hope this helps.
I would first determine if the problem is client side or server side. Your client code looks ok to me, so I would try hitting your server with a simple curl command.
For example:
curl -k -i -H 'Accept: application/json' -H 'Content-type: application/json' -X POST -d '<YOUR POST BODY>' 'http://yourhost/yourendpoint'
This will help determine if it's a purely server side issue, which I suspect in this case it is.
Related
Following is my curl request:
curl -X POST --data-urlencode 'data1#/Users/Documents/file.csv' http://localhost:8000/predict
Following is my equivalent Java implementation.
String filePath = inputFilePath;
String url = inputUrl;
File file = new File(filePath);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost(inputUrl);
uploadFile.addHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
FileBody fileBody = new FileBody(new File(inputFilePath));
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("data1", fileBody)
.build();
uploadFile.setEntity(reqEntity);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(uploadFile);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to invoke my R Rest API endpoint from my Java HTTP post.
#* #post /predict
mypredict <- function(data1) {
print(data1)
}
(1) Is my equivalent Java HTTP Post request correct?
(2) I am able to invoke the R rest endpoint using my curl command. But for some reason when i sent the POST request through my Java code, i see that data1 is not being passed as part of post request. I see this error in R.
<simpleError in print(data1): argument "data1" is missing, with no default>
I feel my Java equivalent curl implementation is wrong. Can someone help?
You specify content-type application/x-www-form-urlencoded (as curl does for this case) but supply an actual body (entity) that corresponds to multipart/form-data which is radically different. Instead use URLEncodedFormEntity containing (for your case) one NameValuePair something like this:
byte[] contents = Files.readAllBytes (new File(filepath).toPath());
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("data1", new String(contents,charset));
uploadFile.setEntity(new UrlEncodedFormEntity (list));
And you don't need addHeader("content-type",...) because setting the entity automatically supplies the content-type header (and content-length).
I'm trying to use apache http components to interface with the Spotify api. The request I'm trying to send is detailed here under #1. When I send this request from bash using curl
curl -H "Authorization: Basic SOMETOKEN" -d grant_type=client_credentials https://accounts.spotify.com/api/token
I get back a token like the website describes
However the following java code, which as far as I can tell executes the same request, gives back a 400 error
Code
String encoded = "SOMETOKEN";
CloseableHttpResponse response = null;
try {
CloseableHttpClient client = HttpClients.createDefault();
URI auth = new URIBuilder()
.setScheme("https")
.setHost("accounts.spotify.com")
.setPath("/api/token")
.setParameter("grant_type", "client_credentials")
.build();
HttpPost post = new HttpPost(auth);
Header header = new BasicHeader("Authorization", "Basic " + encoded);
post.setHeader(header);
try {
response = client.execute(post);
response.getEntity().writeTo(System.out);
}
finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Error
{"error":"server_error","error_description":"Unexpected status: 400"}
The URI that the code prints is looks like this
https://accounts.spotify.com/api/token?grant_type=client_credentials
And the header looks like this
Authorization: Basic SOMETOKEN
Am I not constructing the request correctly? Or am I missing something else?
Use form url-encoding for the data in the body with the content-type application/x-www-form-urlencoded :
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("https://accounts.spotify.com/api/token");
post.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
post.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded);
StringEntity data = new StringEntity("grant_type=client_credentials");
post.setEntity(data);
HttpResponse response = client.execute(post);
So I've got this code:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("url");
StringEntity params = new StringEntity("stuff");
request.addHeader("content-type", "application/json");
//request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//stuff
} catch (Exception ex) {
//stuff
} finally {
httpClient.getConnectionManager().shutdown();
}
I need to create a POST request which I can do with curl -X POST /groups/:group_id/members/add etc but I'm not sure how to add the /groups/ param to my code... I'm not super familiar with how to do this so any advice would be appreciated. Thanks!
EDIT 1: (SOLVED)
Have used the suggested code but would like some help with variables used in the string while remaining valid JSON format, if possible.
EDIT 2:
Using that method, can you show an example of how to add multiple users to that one StringEntity? So like user1 is "User1" and has the email "Email1" and user2 has "User2" and "Email2" etc
Just create a url string using the prams you have and pass it as argument to HttpPost()
DefaultHttpClient httpClient = new DefaultHttpClient();
String groupId = "groupId1";
String URL = "http://localhost:8080/"+groupId+"/members/add"
HttpPost postRequest = new HttpPost(
URL );
StringEntity input = new StringEntity("{\"name\":matt,\"from\":\"stackovefflow\"}");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
UPDATED
The input to StringEntity is a string whihc you can manipulate in any way.
You can define a method like
private createStringEntity(String name, String email){
return new StringEntity("{\"name\":\""+name+"\",\"email\":\""+email+"\"}");
}
The "/groups/..." part is not a parameter but a fraction of the url. I dont think this will work, because "url" is just a String, change it to this:
HttpPost request = new HttpPost("http://stackoverflow.com/groups/[ID]/members/add");
I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.
I send a request from a java code to php server then on server side I just echo what has received as response.
So in theory I will receive what I send. but I have problem on sending UTF-8 contents, when I send arabic characters I receive unexpected characters.
My java request code:
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
String requestString = "سلام";
StringEntity entity = new StringEntity(requestString, "UTF-8");
entity.setContentType("application/json");
entity.setContentEncoding("UTF-8");
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(entity);
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
httpPost.setHeader("Accept-Charset", "utf-8");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpClient httpClient = new DefaultHttpClient(httpParams);
String responseString=null;
try
{
responseString = httpClient.execute(httpPost, responseHandler);
}
catch (IOException e)
{ e.printStackTrace(); }
My code on server side:
<?php
echo file_get_contents('php://input');
?>
In this test I send string "سلام" but in response I receive "سÙاÙ".
I also tried to solve the problem with changing charset with iconv(...) method on php but I failed.
I even don't know the problem is in client or server. Has anybody a help idea?
Answering to my own question:
In my case the problem was in server side. I changed the header of response of server and the problem solved:
header('Content-Type:application/json; charset=utf-8');