java-使用Retrofit2将文件上传到AWS S3预签名URL
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-使用Retrofit2将文件上传到AWS S3预签名URL,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3199字,纯文字阅读大概需要5分钟。
内容图文
我正在尝试使用预先签名的URL将文件上传到Amazon的S3.我从生成URL的服务器获取URL.将其作为JSON对象的一部分发送给我.我将URL作为字符串获取,如下所示:
不幸的是,当我将其传递给Retrofit2时,它修改了String并试图将其制成URL.我已经设置了encoding = true,它可以解决大多数问题,但不能完全解决.我知道字符串按原样工作.我已经在Postman&得到成功的回应.
1st我尝试只是将String(除了我作为baseUrl剪切的东西)整体放入Path
public interface UpdateImageInterface {
@PUT("{url}")
Call<Void> updateImage(@Path(value="url", encoded=true) String url, Body RequestBody image);
}
调用代码:
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);
除“?”外,此方法大部分有效(在“ ImageName”之后)转换为“?”.这会导致请求错误/ 400.
我的下一个尝试是使用Retrofit2创建查询,然后将整个String(带有多个查询)转储到查询中.
public interface UpdateImageInterface {
@PUT("ImageName")
Call<Void> updateProfilePhoto(@Query(value="X-Amz-Security-Token", encoded = true) String token, @Body RequestBody image);
}
调用代码:
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);
这得到“?”正确呈现,但所有的’&’更改为“&”
最后,我尝试在baseUrl()中传递整个String,但是由于结尾没有’/’,因此给出了IllegalArgumentException.
我知道我可以解析预先签名的URL来进行多个查询,在应进行查询的情况下将它们组装在Retrofit2中,但我想避免这种处理.
要重申这个问题:
有没有一种方法可以使用Retrofit2轻松地(无需进行大量的字符串分析)将带有预签名URL的文件上传到S3?
解决方法:
在同事的帮助下,这就是解决方案.
public interface UpdateImageInterface {
@PUT
Call<Void> updateImage(@Url String url, @Body RequestBody image);
}
调用代码:
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);
Javadoc获取@Url(类Url)&
baseUrl()(Retrofit.Builder类)
MediaType是OkHttp库中的一个类,经常与Retrofit(均来自Square)一起使用.可以在Javadoc中找到有关传递给parse方法的常量的信息.
内容总结
以上是互联网集市为您收集整理的java-使用Retrofit2将文件上传到AWS S3预签名URL全部内容,希望文章能够帮你解决java-使用Retrofit2将文件上传到AWS S3预签名URL所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。