Gar*_*y99 3 java android amazon-s3 retrofit2
我正在尝试使用预先签名的URL将文件上传到Amazon的S3。我从生成URL的服务器获取URL,并将其作为JSON对象的一部分发送给我。我将URL作为字符串获取,如下所示:
不幸的是,当我将其传递给Retrofit2时,它修改了String并试图将其制成URL。我已经设置好encoding=true了,可以解决大多数问题,但不能完全解决。我知道字符串按原样工作。我在邮递员中尝试过并获得成功的回应。
1st我尝试仅将String(除了我作为baseUrl剪切的东西)整体放入Path
public interface UpdateImageInterface {
@PUT("{url}")
Call<Void> updateImage(@Path(value="url", encoded=true) String url, Body RequestBody image);
}
Run Code Online (Sandbox Code Playgroud)
调用代码:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://com-example-mysite.s3-us-east-1.amazonaws.com/userFolder/")
.build();
UpdateImageInterface imageInterface = retrofit.create(UpdateImageInterface.class);
// imageUrl is "ImageName..."
Call<Void> call = imageInterface.updateImage(imageUrl, requestFile);
Run Code Online (Sandbox Code Playgroud)
除“?”外,此方法大部分有效 (在“ ImageName”之后)转换为“%3F”。这会导致请求错误/ 400。
我的下一个尝试是使用Retrofit2创建查询,然后将整个String(包含多个查询)转储到查询中。
public interface UpdateImageInterface {
@PUT("ImageName")
Call<Void> updateProfilePhoto(@Query(value="X-Amz-Security-Token", encoded = true) String token, @Body RequestBody image);
}
Run Code Online (Sandbox Code Playgroud)
调用代码:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://com-example-mysite.s3-us-east-1.amazonaws.com/userFolder/")
.build();
UpdateImageInterface imageInterface = retrofit.create(UpdateImageInterface.class);
// imageUrl is "xxfooxx..."
Call<Void> call = imageInterface.updateImage(imageUrl, requestFile);
Run Code Online (Sandbox Code Playgroud)
这得到“?” 正确呈现,但所有的“&”都更改为“%26”
最后,我尝试将整个String传入,baseUrl()但是由于结尾没有'/'而给出了IllegalArgumentException。
我知道我可以解析预签名的URL来进行多个查询,并在Retrofit2中将它们组合起来,因为应该执行查询,但是我想避免这种处理。
要重申这个问题:
有没有一种方法可以使用Retrofit2轻松地(无需进行大量的字符串分析)将带有预签名URL的文件上传到S3?
在同事的帮助下,这就是解决方案。
public interface UpdateImageInterface {
@PUT
Call<Void> updateImage(@Url String url, @Body RequestBody image);
}
Run Code Online (Sandbox Code Playgroud)
调用代码:
String CONTENT_IMAGE = "image/jpeg";
File file = new File(localPhotoPath); // create new file on device
RequestBody requestFile = RequestBody.create(MediaType.parse(CONTENT_IMAGE), file);
/* since the pre-signed URL from S3 contains a host, this dummy URL will
* be replaced completely by the pre-signed URL. (I'm using baseURl(String) here
* but see baseUrl(okhttp3.HttpUrl) in Javadoc for how base URLs are handled
*/
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.dummy.com/")
.build();
UpdateImageInterface imageInterface = retrofit.create(UpdateImageInterface.class);
// imageUrl is the String as received from AWS S3
Call<Void> call = imageInterface.updateImage(imageUrl, requestFile);
Run Code Online (Sandbox Code Playgroud)
Javadoc获取有关@Url(类URL)和
baseUrl()(类Retrofit.Builder)的信息
MediaType是OkHttp库中的一个类,通常与Retrofit(均来自Square)一起使用。可以在Javadoc中找到有关传递给parse方法的常量的信息。
| 归档时间: |
|
| 查看次数: |
1994 次 |
| 最近记录: |