我想从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的一部分.
不幸的是,我没有提供示例的源代码,但希望它将为您指明正确的方向.
总结以上是内存溢出为你收集整理的Java-最佳方法:从Android到GAE的HTTP POST(多部分)全部内容,希望文章能够帮你解决Java-最佳方法:从Android到GAE的HTTP POST(多部分)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)