Alexander Bolinsky Alexander Bolinsky - 24 days ago 10
PHP Question

How to pass an argument with POST using HttpUrlConnection

EDIT: I figure out that wrapping the OutputStreamWriter in a BufferedWriter was causing the problem, so got rid of the wrapper and my POST goes through. Still wondering why the BufferedWriter was the cause.

I apologize in advance, as I am just beginning to teach myself all about databases, communication between an app and a server/database, and php.

Other similar questions asked have not provided an answer.

I am having some trouble discerning what I'm missing when it comes to making a simple POST using HttpUrlConnection from my android application to a php script on a locally hosted server. I need to take a user ID from the android application, pass that to the php script as an argument, and perform a lookup of that ID in the database table called users. I also would like to use methods and classes that are not deprecated.

I have included Internet permissions in the android manifest. I am using XAMPP, and I have verified that my servers are running, and if I access the url through a web browser I get the JSON response I am looking for.

My only logcat message is an IOException, which occurs just after writing to the output stream. EDIT: The specific exception is "unexpected end of stream".

Here is the code in my AsyncTask class:

protected String doInBackground(String... params) {

String userID = params[0];
Pair<String, String> phpParameter = new Pair<>("userID", userID);
String result = "";

try {
URL url = new URL("url of locally-hosted php script");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

// prepare request
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setFixedLengthStreamingMode(userID.getBytes("UTF-8").length);

// upload request
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(phpParameter.first + "=" + phpParameter.second);
writer.close();
outputStream.close();

// read response
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));

String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) { response.append(inputLine); }
in.close();

result = response.toString();

// disconnect
urlConnection.disconnect();
} catch (MalformedURLException e) {
Log.e("Malformed URL Exception", "Malformed URL Exception");
} catch (IOException e) {
Log.e("IOException", "IOException");
}

return result;
}


And here is my php script on the server. I also need a little help with prepared statements, so don't beat me up over the 'id = 1':

<?php

mysql_connect("host","username","password");

mysql_select_db("Database");

print($_POST);

$sql = mysql_query("select * from users where id = 1");

while($row = mysql_fetch_assoc($sql))
$output[] = $row;

print(json_encode($output)); // this will print the output in json
mysql_close();

?>

Answer

Looks like I fixed it!

I changed

BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(phpParameter.first + "=" + phpParameter.second);

to

OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
writer.write(userID);

For some reason, the act of wrapping the output stream writer in a buffered writer was breaking it. I don't know why.

Once I made the above change, I received an error saying that the stream was expecting 1 byte but received 8, so I wrote only userID, which is what I passed to setFixedLengthStreamingMode anyway.

Comments