I've written code to send data to the server from an app using the HttpURLConnection library. This code is working correctly. But when I want to show the information sent to the server in the browser, nothing is displayed. Where is the problem? please guide me. The code written below is shown below.
Android code:
String message = null;
try {
Log.d("SENDSTEP","1");
message = URLEncoder.encode("lat"+ "=" + 123456, "UTF-8");
Log.d("SENDSTEP","2");
try {
// instantiate the URL object with the target URL of the resource to
// request
Log.d("SENDSTEP","3");
URL url = new URL("http://www..../UploadToServer.php");
// instantiate the HttpURLConnection with the URL object - A new
// connection is opened every time by calling the openConnection
// method of the protocol handler for this URL.
// 1. This is the point where the connection is opened.
Log.d("SENDSTEP","4");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
// set connection output to true
Log.d("SENDSTEP","5");
connection.setDoOutput(true);
// I will use this to get a string response from the PHP script, using InputStream below.
connection.setDoInput(true);
// instead of a GET, we're going to send using method="POST"
connection.setRequestMethod("POST");
// instantiate OutputStreamWriter using the output stream, returned
// from getOutputStream, that writes to this connection.
// 2. This is the point where you'll know if the connection was
// successfully established. If an I/O error occurs while creating
// the output stream, you'll see an IOException.
Log.d("SENDSTEP","6");
OutputStreamWriter writer = new OutputStreamWriter(
connection.getOutputStream());
Log.d("SENDSTEP","7");
// write data to the connection. This is data that you are sending
// to the server
// 3. No. Sending the data is conducted here. We established the
// connection with getOutputStream
writer.write( message);
Log.d("SENDSTEP","8");
// Closes this output stream and releases any system resources
// associated with this stream. At this point, we've sent all the
// data. Only the outputStream is closed at this point, not the
// actual connection
writer.close();
Log.d("SENDSTEP","9");
// if there is a response code AND that response code is 200 OK, do
// stuff in the first if block
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
Log.d("SENDSTEP","OK");
// otherwise, if any other status code is returned, or no status
// code is returned, do stuff in the else block
} else {
// Server returned HTTP error code.
Log.d("SENDSTEP","No");
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PHP code:
<?php
echo "OK";
echo $_POST["message"];
echo "OK";
echo $_POST["lat"];
echo "OK";
?>