我想从Android相机上捕获图像,然后将其发送到Google App Engine,后者会将图像存储在Blob存储区中.听起来很简单,我可以进行到GAE的多部分POST,但是存储到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();
}
}
尽我所能,此代码不会跟随重定向.输入的蒸汽始终为空,响应始终为302.尽管图像很好地上传.如果有人可以告诉我我可以做些什么使它跟随重定向以便我可以阅读响应,我将不胜感激.
另外,如果有更好的方法,我很想听听.我知道那里有像Apache HTTP Client这样的库,但是它需要太多的依赖项,对于一个简单的任务来说似乎太过膨胀了.
谢谢
解决方法:
几个月前,我试图做完全一样的事情!
基本上,不要使用HttpURLConnection.相反,请使用org.apache.http包中的HttpClient和HttpGet,它们是Android SDK的一部分.
不幸的是,我没有提供示例的源代码,但希望它将为您指明正确的方向.