【发布时间】:2016-04-08 17:20:43
【问题描述】:
我有一个 Endpoints API 方法,它为我提供了一个到 Google Cloud Storage 的上传 URL,如下所示:
@ApiMethod(name = "getUploadUrl", path = "get_upload_url", httpMethod = ApiMethod.HttpMethod.POST)
public CollectionResponse<String> getUploadUrl(@Named("objectName")String objectName){
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
String callbackUrl = "/handleupload";
String uploadUrl = blobstoreService.createUploadUrl(callbackUrl,
UploadOptions.Builder.withGoogleStorageBucketName("my-bucket"));
ArrayList<String> results = new ArrayList<>(1);
results.add(uploadUrl);
return CollectionResponse.<String>builder().setItems(results).build();
}
这成功返回了一个 URL 供我上传我的图像文件。
在 Android 中,我尝试像这样上传文件:
private Boolean uploadImage(File file, String uploadUrl){
try {
long bytes = file.length();
URL url = new URL(uploadUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Connection", "Keep-Alive");
urlConnection.setRequestProperty("Content-Type", "image/jpg");
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
int bytesAvailable = 0;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
bytesAvailable = fileInputStream.available();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[ ] buffer = new byte[bufferSize];
int 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);
}
int responseCode = urlConnection.getResponseCode();
fileInputStream.close();
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
但我收到了400 Bad Request 的回复。我想我做错了什么。
我想使用 HttpURLConnection 类,因为 Android 推荐它而不是 HttpClient(这是大多数 SO 帖子的示例):http://android-developers.blogspot.com/2011/09/androids-http-clients.html
我正在使用 blobstore api 上传图片而不是 Google Cloud Storage 签名 URL,因为我可以获得回调服务器端来处理上传。
【问题讨论】:
标签: android google-app-engine google-cloud-storage