使用Blob存儲區API與HttpURLConnection的我有一個端點API方法,讓我上傳的網址,以谷歌雲存儲這樣的:上傳到谷歌雲存儲中的Android
@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();
}
這成功返回一個網址給我要上傳我的圖像文件。
在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
(這是最讓帖子有例子):http://android-developers.blogspot.com/2011/09/androids-http-clients.html
,我使用Blob存儲區API來上傳圖片,而不是谷歌的Cloud Storage簽名的URL,因爲我可以通過回調服務器端來處理上傳。