【发布时间】:2016-01-13 18:33:17
【问题描述】:
我在从我的 Android 应用程序向我的网络服务(Google Cloud 和 PHP)发出正确的 POST 请求时遇到一些问题。
当我尝试从 Android 发送图像时,它会返回“200 OK”响应,但该图像未保存在 Google Cloud Storage 的存储桶中。我知道问题出在我在 Android 应用程序中的方法发出的 POST 请求上,因为我已经用 Postman 进行了测试,并让它毫无问题地工作。所以我的应用程序的以下代码有问题:
public void uploadFile(String uploadUrl, String filename, String newFileName) throws IOException {
FileInputStream fileInputStream = new FileInputStream(new File(filename));
URL url = new URL(uploadUrl);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"img\";filename=\"" + filename + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
System.out.println(serverResponseMessage);
System.out.println(serverResponseCode);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
我已经测试过所有参数都是 100% 正确的,所以你不必担心。
如果您需要从 Web 服务中查看 PHP 代码以接收请求,这里是:
<?php
$img = $_FILES['img']['tmp_name'];
move_uploaded_file($img, 'gs://routeimages/yeeeeeeees.jpg');
echo "done";
?>
这段代码的问题可能出在哪里?
附加
我还需要在文件/图像之外添加一些文本。如何将此添加到请求中?
【问题讨论】:
-
name=\"img\";filename=\""我看到路径中有一个分号。这是为什么?无论如何,对于图像上传用户多部分数据。此答案中的详细信息...stackoverflow.com/questions/21553507/…
标签: php android post httpurlconnection