gpt4 book ai didi

android - 带有 Android Retrofit V2 库的 AWS S3 Rest API,上传的图像已损坏

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:59:37 26 4
gpt4 key购买 nike

我正在尝试将 Image 从我的 Android APP 上传到 Amazon AWS S3,我需要使用 AWS Restful API

我正在使用 Retrofit 2提出要求。

我的应用程序成功连接到 Amazon S3 并按预期执行请求,但是当我尝试从 Bucket 查看 Image 时,图片打不开。我将 Image 下载到我的电脑并尝试打开,但不断收到图像已损坏的消息。

下面让我们看看我的完整代码。

我的 Gradle 依赖项

compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta1'
compile 'net.danlew:android.joda:2.8.2'

这里创建了一个文件并开始请求

File file = new File(mCurrentPhotoPath);
RequestBody body = RequestBody.create(MediaType.parse("image/jpeg"), file);
uploadImage(body, "photo_name.jpeg");

改造界面

public interface AwsS3 {

@Multipart
@PUT("/{Key}")
Call<String> upload(@Path("Key") String Key,
@Header("Content-Length") long length,
@Header("Accept") String accept,
@Header("Host") String host,
@Header("Date") String date,
@Header("Content-type") String contentType,
@Header("Authorization") String authorization,
@Part("Body") RequestBody body);
}

用于安装凭据的实用程序类

public class AWSOauth {

public static String getOAuthAWS(Context context, String fileName) throws Exception{

String secret = context.getResources().getString(R.string.s3_secret);
String access = context.getResources().getString(R.string.s3_access_key);
String bucket = context.getResources().getString(R.string.s3_bucket);

return gerateOAuthAWS(secret, access, bucket,fileName);
}

private static String gerateOAuthAWS(String secretKey, String accessKey, String bucket, String imageName) throws Exception {

String contentType = "image/jpeg";

DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z").withLocale(Locale.US);
String ZONE = "GMT";
DateTime dt = new DateTime();
DateTime dtLondon = dt.withZone(DateTimeZone.forID(ZONE)).plusHours(1);
String formattedDate = dtLondon.toString(fmt);

String resource = "/" + bucket + "/" + imageName;

String stringToSign = "PUT" + "\n\n" + contentType + "\n" + formattedDate + "\n" + resource;

Mac hmac = Mac.getInstance("HmacSHA1");
hmac.init(new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA1"));

String signature = ( Base64.encodeToString(hmac.doFinal(stringToSign.getBytes("UTF-8")), Base64.DEFAULT)).replaceAll("\n", "");

String oauthAWS = "AWS " + accessKey + ":" + signature;

return oauthAWS;
}
}

最后是发起请求的方法

 public void uploadImage(RequestBody body, String fileName){

String bucket = getString(R.string.s3_bucket);

Retrofit restAdapter = new Retrofit.Builder()
.baseUrl("http://" + bucket + ".s3.amazonaws.com")
.addConverterFactory(GsonConverterFactory.create())
.build();

AwsS3 service = restAdapter.create(AwsS3.class);

DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE', 'dd' 'MMM' 'yyyy' 'HH:mm:ss' 'Z").withLocale(Locale.US);
String ZONE = "GMT";
DateTime dt = new DateTime();
DateTime dtLondon = dt.withZone(DateTimeZone.forID(ZONE)).plusHours(1);
String formattedDate = dtLondon.toString(fmt);

try {

String oauth = AWSOauth.getOAuthAWS(getApplicationContext(), fileName);

Call<String> call = service.upload(fileName, body.contentLength(), "/**", bucket + ".s3.amazonaws.com", formattedDate, body.contentType().toString(), oauth, body);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Response<String> response) {
Log.d("tag", "response : " + response.body());
}

@Override
public void onFailure(Throwable t) {
Log.d("tag", "response : " + t.getMessage());
}
});

} catch (Exception e) {
e.printStackTrace();
}
}

非常感谢任何帮助,在此先感谢!

最佳答案

我用过Retrofit 2 resolve并且我在界面中使用 Body 而不是 Part 作为你的 RequestBody

@PUT("")
Call<String> nameAPI(@Url String url, @Body RequestBody body);

和java代码

// Prepare image file
File file = new File(pathImg);
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);

Call<String> call = SingletonApiServiceS3.getInstance().getService().nameAPI(
path,
requestBody
);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, final Response<String> response) {

if (response.isSuccessful()) {
// Your handling
} else {
// Your handling
}
}

@Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(getContext(), "onFailure : "+t.getMessage().toString(),Toast.LENGTH_SHORT).show();
}
});

关于android - 带有 Android Retrofit V2 库的 AWS S3 Rest API,上传的图像已损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32663281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com