在Android中获取请求PHP的响应

时间:2016-09-13 21:35:28

标签: java php android

我在Android proyect的asynctask中有这个代码,用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();

这是服务器端的PHP代码:

$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";
}

一切正常,文件上传正确但是服务器在下面的代码行中给出的唯一响应:

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

是:

  

服务器响应是:OK:200

或者:

  

服务器响应是:未找到:404

我想获得服务器端出现的字符串“成功”“失败”,我该怎么做?提前谢谢。

2 个答案:

答案 0 :(得分:1)

是的HttpUrlConnection#getResponseMessage只返回HTTP响应消息(即200 = HTTP OK)。你想做的是:

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


// read the contents of the connection from the bufferedreader

答案 1 :(得分:0)

.getResponseMessage()是HTTP状态消息,而不是请求的输出。

您需要使用其他功能,例如connection.getContent()或循环connection.getInputStream()

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