send data through post from android to node.js? - java

I use nodejs as server and java(android) as client,i succes send data through post from android to node. but my problem when android send the data (string) consist of space and new line (enter) its received on node but the character was change,
for example,i send this string from android
Hello
I learn android
the string send to node and received,but i get this in node
Hello%0AI+learn+android
I use this code for send string to node in android.
public void btnOnClick(){
String text= URLEncoder.encode(editText.getText().toString(), "utf-8"); //I get from editText and convert to utf-8
sendToNode(text);
}
public void sendToNode(String text){
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myDomain.com:8888/");
UrlEncodedFormEntity form;
try {
Log.i("kirim ke node isitextAsli ",text);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("datanah",text));
form=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
httppost.setEntity(form);
HttpResponse response = httpclient.execute(httppost);
Log.i("HTTP Post", "Response from server node = " + response.getStatusLine().getReasonPhrase() + " Code = " + response.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
Log.e("HTTP Post", "Protocol error = " + e.toString());
} catch (IOException e) {
Log.e("HTTP Post", "IO error = " + e.toString());
}
}
and I use this code for receive string in node
req.addListener('data', function(chunk) { data += chunk; });
req.addListener('end', function() {
console.log("from android :"+data); //result of data is Hello%0AI+learn+android
});
How i solve my problem?
please help,Thanks.

The string is URL-encoded, as you explicitly asked for in your code (and need for a regular POST). Decode it on the server.
To decode it on the server side, do:
var querystring = require('querystring');
querystring.unescape(data.replace(/\+/g, " "));

The following is the sample of encoding and decoding, YOU WANT TO DECODE IN THE SERVER PART
String encoded;
try {
encoded = URLEncoder.encode(input, "UTF-8");
System.out.println("URL-encoded by client with UTF-8: " + encoded);
String incorrectDecoded = URLDecoder.decode(encoded, "ISO-8859-1");
System.out.println("Then URL-decoded by server with ISO-8859-1: " + incorrectDecoded);
String correctDecoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Server should URL-decode with UTF-8: " + correctDecoded);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Related

REST call returns 200 but no desired change due to POST

I have the below response from a REST call when used with postman.The Response code is 200 :
I am trying to write some code to make the REST call :
HttpHost httpHostTag = getMMCHost(prop);
System.out.println(httpHostTag);
//#SuppressWarnings("deprecation")
DefaultHttpClient httpclient = (DefaultHttpClient) verifiedClient(new DefaultHttpClient());
HttpGet httpostTag = verifiedGet(urlTagUpdate, Mmc_user, Mmc_password);
HttpResponse response = httpclient.execute(httpHostTag, httpostTag);
System.out.println(response.getParams());
int respCode = response.getStatusLine().getStatusCode();
System.out.println("response Code for Tag Update API Call : " + respCode);
String Code = Integer.toString(respCode);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
//resultMsg = result.split(",")[0].split(":")[1];
resultMsg = result.split(",")[0].split("msg")[1];
System.out.println(resultMsg);
System.out.println("RESPONSE: " + result);
instream.close();
}
if (Code.equals("200") || Code.equals("202") || Code.equals("204")) {
System.out.println(resultMsg);
// return "RESPONSE : " + resultMsg;
} else {
return "Error : " + result;
}
} catch (Exception e) {
System.out.println("error in code ");
e.printStackTrace();
}
System.out.println("Tag Update to setenv.sh .................. This will take around 10 sec ");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// you probably want to quit if the thread is interrupted
}
return null;
}
In the split msg section above, I am getting errors. Nevertheless, even if I comment that section of the code,I am able to make the REST call. The call goes through and returns 200 as code. But it doesnot do any change as the REST call is supposed to do.
The REST url is correct as through POSTMAN it works perfect.
Any idea where I am making a mistake in the above code ?

how to send file with httprequest in java?

how to send file with http request in java ?
i see question
Send image file using java HTTP POST connections
and
Upload files from Java client to a HTTP server
but them are too old question and not work any more .
A good example is given in Multi part File Upload example of Apache HttpClient
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/MultipartFileUploadApp.java?view=markup
The part that actually posts the file is
String targetURL = cmbURL.getSelectedItem().toString();
// add the URL to the combo model if it's not already there
if (!targetURL
.equals(
cmbURLModel.getElementAt(
cmbURL.getSelectedIndex()))) {
cmbURLModel.addElement(targetURL);
}
PostMethod filePost = new PostMethod(targetURL);
filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
cbxExpectHeader.isSelected());
try {
appendMessage("Uploading " + targetFile.getName() + " to " + targetURL);
Part[] parts = {
new FilePart(targetFile.getName(), targetFile)
};
filePost.setRequestEntity(
new MultipartRequestEntity(parts, filePost.getParams())
);
HttpClient client = new HttpClient();
client.getHttpConnectionManager().
getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
appendMessage(
"Upload complete, response=" + filePost.getResponseBodyAsString()
);
} else {
appendMessage(
"Upload failed, response=" + HttpStatus.getStatusText(status)
);
}
} catch (Exception ex) {
appendMessage("ERROR: " + ex.getClass().getName() + " "+ ex.getMessage());
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
Hope it is of some help to you.

Sending location data from android app to apache server

I have created an app that takes the current location of the phone and then should send it to an apache web server. I'm using a php file on the server to receive the data and then write it to an HTML file. The domain works fine, and it properly displays the html file that I have on the web server, but the php file does not write the data to the html file and I'm not sure why.
Here is the code for sending the data
if (currentLocation == null) {
return;
}
else {
//Creating strings for the latitude and longitude values of our current location
String latitude = new String(" " + (Math.round(currentLocation.getLatitude()*10000000))/10000000);
String longitude = new String(" " + (Math.round(currentLocation.getLatitude()*10000000))/10000000);
// Creating an http client and http post object in order to interact with server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://findmylocation.chandlermatz.com/");
try {
//Creating identifier and value pairs for the information we want to send to server
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Latitude", latitude));
nameValuePairs.add(new BasicNameValuePair("Longitude", longitude));
//Sending data to server via http client
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
And here is my php code
<?php
// get the "message" variable from the post request
// this is the data coming from the Android app
$latitude = $_POST["Latitude"];
$longitude = $_POST["Longitude"];
// specify the file where we will save the contents of the variable message
$filename="index.html";
// write (append) the data to the file
file_put_contents($filename,date('m/d/Y H:i:s') . " &nbsp &nbsp &nbsp" . $latitude . " &nbsp " . $longitude . "<br />",FILE_APPEND);
?>
Any help is appreciated!

Why wont my HTTP POST request send to my webpage?

Ive looked at a lot of other threads here and all over the internet and I cant seem to solve this..
So basically I have written this Java code:
public void sendReport(CommandSender sender, Player target, String reason)
{
HttpURLConnection connectionStandard = null;
String email = config.getString("rp.site.email");
String password = config.getString("rp.site.password");
String senderName = sender.getName();
String targetName = target.getDisplayName();
String reasonString = reason;
try
{
URL url = new URL("http://www.website.net/folder/connect.php");
HttpURLConnection request = (HttpURLConnection)url.openConnection();
request.setRequestProperty("Content-type","application/x-www-form-urlencoded");
request.setRequestMethod("POST");
request.setDoOutput(true);
OutputStreamWriter post = new OutputStreamWriter(request.getOutputStream());
String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email.toString(), "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password.toString(), "UTF-8");
data += "&" + URLEncoder.encode("reporter", "UTF-8") + "=" + URLEncoder.encode(senderName, "UTF-8");
data += "&" + URLEncoder.encode("reported", "UTF-8") + "=" + URLEncoder.encode(targetName, "UTF-8");
data += "&" + URLEncoder.encode("reason", "UTF-8") + "=" + URLEncoder.encode(reasonString, "UTF-8");
post.write(data);
post.flush();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if(null != connectionStandard)
{
connectionStandard.disconnect();
}
}
}
and basically, my php code just looks like this:
<?php
require_once "db.php";
$reporter->startSecureSession();
foreach ($_POST as $post => $value) {
$post = strip_tags($post);
$value = strip_tags($value);
}
if(!(isset($_POST['email'])) or (!isset($_POST['password'])) or (!isset($_POST['reporter'])) or (!isset($_POST['reported'])) or (!isset($_POST['reason']))) {
exit("Invalid Request");
}
$password = hash("sha512", $_POST['password']);
$reporter->login(array("email" => $_POST['email'], "password" => $password), "plugin");
if($reporter->validateClient()) {
$reporter->sendReport($_POST);
header("Location: logout.php");
exit();
} else {
exit();
}
?>
When I send my details through chrome to the web page, it works and sends stuff to my database, but when I do it off my bukkit server through the command that sends the request, it doesnt :/
Thanks for the help :)
You can use Apache httpclient 4.x to send GET/POST request from Java.
String url = "http://www.website.net/folder/connect.php";
HttpPost method = new HttpPost(url);
HttpClient httpClient = new DefaultHttpClient();
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
formparams.add(new BasicNameValuePair("email", email.toString()));
formparams.add(new BasicNameValuePair("password", password.toString()));
formparams.add(new BasicNameValuePair("reporter", senderName));
formparams.add(new BasicNameValuePair("reported", targetName));
formparams.add(new BasicNameValuePair("reason", reasonString));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(formparams, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
method.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(method);
Well, from the javadoc of URLConnection:
1) The connection object is created by invoking the openConnection method
on a URL.
2) The setup parameters and general request properties are
manipulated.
3) The actual connection to the remote object is made, using
the connect method.
4) The remote object becomes available. The header
fields and the contents of the remote object can be accessed.
You do not appear to have called URLConnection#connect.

How do I send an image file in a Http POST request? (java)

So I'm writing a small app to dump a directory of images into the user's tumblr blog, using their provided API: http://www.tumblr.com/docs/en/api
I've gotten plaintext posting to work, but now I need to find out how to send an image file in the POST instead of UTF-8 encoded text, and I'm lost. My code at the moment is returning a 403 forbidden error, as if the username and password were incorrect (they're not), and everything else I try gives me a bad request error. I'd rather not have to use external libraries for this if I can. This is my ImagePost class:
public class ImagePost {
String data = null;
String enc = "UTF-8";
String type;
File img;
public ImagePost(String imgPath, String caption, String tags) throws IOException {
//Construct data
type = "photo";
img = new File(imgPath);
data = URLEncoder.encode("email", enc) + "=" + URLEncoder.encode(Main.getEmail(), enc);
data += "&" + URLEncoder.encode("password", enc) + "=" + URLEncoder.encode(Main.getPassword(), enc);
data += "&" + URLEncoder.encode("type", enc) + "=" + URLEncoder.encode(type, enc);
data += "&" + URLEncoder.encode("data", enc) + "=" + img;
data += "&" + URLEncoder.encode("caption", enc) + "=" + URLEncoder.encode(caption, enc);
data += "&" + URLEncoder.encode("generator", "UTF-8") + "=" + URLEncoder.encode(Main.getVersion(), "UTF-8");
data += "&" + URLEncoder.encode("tags", "UTF-8") + "=" + URLEncoder.encode(tags, "UTF-8");
}
public void send() throws IOException {
// Set up connection
URL tumblrWrite = new URL("http://www.tumblr.com/api/write");
HttpURLConnection http = (HttpURLConnection) tumblrWrite.openConnection();
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "image/png");
DataOutputStream dout = new DataOutputStream(http.getOutputStream());
//OutputStreamWriter out = new OutputStreamWriter(http.getOutputStream());
// Send data
http.connect();
dout.writeBytes(data);
//out.write(data);
dout.flush();
System.out.println(http.getResponseCode());
System.out.println(http.getResponseMessage());
dout.close();
}
}
I suggest you use MultipartRequestEntity (successor of deprecated MultipartPostMethod) of the Apache httpclient package. With MultipartRequestEntity you can send a multipart POST request including a file. An example is below:
public static void postData(String urlString, String filePath) {
log.info("postData");
try {
File f = new File(filePath);
PostMethod postMessage = new PostMethod(urlString);
Part[] parts = {
new StringPart("param_name", "value"),
new FilePart(f.getName(), f)
};
postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
HttpClient client = new HttpClient();
int status = client.executeMethod(postMessage);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Categories