繁体   English   中英

从 Android 中的请求 PHP 获取响应

[英]Get response from request PHP in 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

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

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

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


// read the contents of the connection from the bufferedreader

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

您需要使用不同的函数,例如connection.getContent()或循环connection.getInputStream()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM