UTF-8 content Java request and PHP response - java

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');

Related

How can I send JSON data to Logstash

I know there is a Logstash http input plugin.
I am wondering if it is possible to send JSON message to Logstash using Java.
I do something like this:
HttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("host_name:port/index_name/type_name");
StringEntity params = new StringEntity("{\"message\": {\"fieldName\":\"value\"}}");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
} catch (Exception ex) {
}
}
but data is not sent to Logstash.
Could anybody recommend the correct way to do that?

HTTP post/API request works when sent from CURL on bash, fails from Apache http

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);

Use Java to get Github repositories

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.

node.js req.body empty when sending from java with httpPost

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.

Google authentication with Java apache http tokens

I'm trying to authenticate with Google using a simple Java program. I post to the correct URL with my credentials. I get a response with HTTP status code 200 but that doesn't contain any of the authentication tokens that I need to retrieve feeds for the user. Here's the code
private static String postData = "https://www.google.com/accounts/ClientLogin?Content-type=application/x-www-form-urlencoded&accountType=GOOGLE&Email=xxxxxxxx&Passwd=xxxxx";
public GoogleConnector(){
HttpClient client=new DefaultHttpClient();
HttpPost method=new HttpPost(postData);
try{
HttpResponse response=client.execute(method);
System.out.println(response.toString());
}
catch(Exception e){
}
Ok, the first problem you have is that 'Content-Type' needs to be a header, not a request parameter. And secondly, POST parameters should be appended to the request body, not to the request URL. Your code should look something like this:
HttpClient client = new DefaultHttpClient();
HttpPost method = new HttpPost("https://www.google.com/accounts/ClientLogin");
method.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>(4);
postParams.add(new BasicNameValuePair("accountType", "GOOGLE"));
postParams.add(new BasicNameValuePair("Email", "xxxxxxx"));
postParams.add(new BasicNameValuePair("Passwd", "xxxxxx"));
postParams.add(new BasicNameValuePair("service", "cl"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParams);
method.setEntity(formEntity);
HttpResponse response=client.execute(method);
System.out.println(response.toString());

Categories