JoriusR JoriusR - 2 months ago 23
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.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
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);

dataOutputStream.writeBytes(lineEnd);

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

while (bytesRead > 0){
dataOutputStream.write(buffer,0,bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable,maxBufferSize);
bytesRead = fileInputStream.read(buffer,0,bufferSize);
}

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

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

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


fileInputStream.close();
dataOutputStream.flush();
dataOutputStream.close();


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


Or:


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

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