JoriusR JoriusR - 1 year ago 102
PHP Question

Get response from request PHP in Android

I have this code in an asynctask in my android proyect to upload a file to server with PHP:

URL url = new URL(args[1]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("ENCTYPE", "multipart/form-data");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
connection.setRequestProperty("uploaded_file", args[0]);

dataOutputStream = new DataOutputStream(connection.getOutputStream());

dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + args[0] + "\"" + lineEnd);


bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
buffer = new byte[bufferSize];
bytesRead =,0,bufferSize);

while (bytesRead > 0){
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead =,0,bufferSize);

dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();

Log.d(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);


This is the PHP code in the server side:

$file_path = "./uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path) ){
echo "success";
} else{
echo "fail";

Everything works fine, the file is uploaded correctly but the only response that the server gives me in the code line below:

Log.d(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

It is:

Server Response is: OK: 200


Server Response is: NOT FOUND: 404

I wanna get the strings "success" and "fail" that appears in the server side, How can I do that? Thanks in advance.

Answer Source

Yeah HttpUrlConnection#getResponseMessage just returns the HTTP Response Message (i.e. 200 = HTTP OK). What you want to do is something like:

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

// read the contents of the connection from the bufferedreader
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download