gpt4 book ai didi

java - 最佳方法 : HTTP POST (multi-part) from Android to GAE

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:47 25 4
gpt4 key购买 nike

我想从 Android 上的相机捕捉图像,并将其发送到 Google App Engine,后者会将图像存储在 blob 存储中。听起来很简单,我可以让多部分 POST 到 GAE 发生,但存储到 Blob 存储需要 servlet 返回 HTTP 重定向 (302)。因此,我需要一个可以在执行 HTTP POST 后遵循重定向的连接。这是我希望可以工作的代码:

public static String sendPhoto(String myUrl, byte[] imageData) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = "/data/file_to_send.jpg";
String urlServer = myUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// Please follow redirects
HttpURLConnection.setFollowRedirects(true);
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
try {
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// I really want you to follow redirects
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(10000); // 10 sec
connection.setReadTimeout(10000); // 10 sec
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.connect();
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name="
+ "\"file1\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.write(imageData);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
outputStream.flush();
outputStream.close();
rd = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
Log.i("Response: ", sb.toString());
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Response: serverResponseCode:",
String.valueOf(serverResponseCode));
Log.i("Response: serverResponseMessage:", serverResponseMessage);
} catch (Exception ex) {
ex.printStackTrace();
}
}

尽我所能,此代码不会遵循重定向。输入 steam 始终为空,响应始终为 302。尽管图片上传得很好。如果有人可以告诉我如何使它遵循重定向以便我可以阅读响应,我将不胜感激。

或者,如果有更好的方法,我很想听听。我知道那里有像 Apache HTTP Client 这样的库,但它需要如此多的依赖项,对于一项简单的任务来说似乎过于臃肿。

谢谢

最佳答案

几个月前我也在尝试做同样的事情!

基本上,不要使用HttpURLConnection。相反,请使用 org.apache.http 包中的 HttpClientHttpGet,它们是 Android SDK 的一部分。

很遗憾,我没有源代码来提供示例,但希望这能为您指明正确的方向。

关于java - 最佳方法 : HTTP POST (multi-part) from Android to GAE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3270336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com