我在我的 android proyect 的异步任务中有这段代码,用于使用 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);
它是:
Server Response is: OK: 200
或者:
Server Response is: NOT FOUND: 404
我想获取服务器端出现的字符串"success" 和"fail",我该怎么做?提前致谢。
最佳答案
是的 HttpUrlConnection#getResponseMessage
只是返回 HTTP 响应消息(即 200 = HTTP OK)。你想要做的是这样的:
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// read the contents of the connection from the bufferedreader
关于java - 从 Android 中的请求 PHP 获取响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39479366/