java - 从 Android 中的请求 PHP 获取响应

标签 java php android

我在我的 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/

相关文章:

android - 在添加新对象之前删除 GridLayout 中的对象

android - 如何在 Genymotion 模拟器上测试 IME_ACTION_DONE

java - 如何调用这个类?

java - ';'预计在 if 之后

java - VBox 内容未填充窗口

javascript - 使用 Ajax 从 jQuery 调用 PHP 脚本来创建新文件夹

php - 解析部分 html 字符串并隔离特定数字

PHP 图表库 VS JavaScript 图表库

java - 正则表达式从字符串中查找特定模式字符串

android - 在 Android 中使用 HTML5 日期输入元素