gpt4 book ai didi

android - 如何为rxjava2 androidnetworking POST请求传递多部分body参数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:13 26 4
gpt4 key购买 nike

我一直在努力找出如何通过post请求的主体传递文件。我在网上试了一些东西,但没有什么能和我的用例完全匹配。
这是我的服务器代码的邮递员屏幕截图:
enter image description here
所以,正如你所看到的,“photo”在body部分是一个键(文件),值是一个图像文件。这是一个post请求,在查询成功时不返回任何响应(只显示创建时的状态,如屏幕截图所示)[另请注意:它需要auth token作为header param,userid作为path param)
终结点代码:

static final String ENDPOINT_UPLOAD_PROFILE_PHOTO= BuildConfig.BASE_URL
+ "/service-profile/v1/member/photo/{userId}";

现在,我使用以下代码块上载照片:
@Override
public Single<JSONObject> doUploadPhoto(String userId, File filepath) {

Rx2ANRequest.MultiPartBuilder post = Rx2AndroidNetworking.upload(ApiEndPoint.ENDPOINT_UPLOAD_PROFILE_PHOTO)
.addMultipartFile("photo",filepath)

.addHeaders("Authorization", mApiHeader.getFormattedProtectedApiHeader())
.addHeaders("content-type", "multipart/form-data")
.setPriority(Priority.HIGH)

.addMultipartParameter("photo",filepath.getAbsolutePath())
.addPathParameter("userId",userId);


return post.build()
.getObjectSingle(JSONObject.class);

}
现在我在我的演示者中引用如下:
        File file = new File(AppPreferencesHelper.getInstance().getPhotoFile());
//preferences has the path of the file , something like : /storage/emulated/0/DCIM/1566415330315.jpg

getCompositeDisposable().add(getDataManager().updateCurrentUserPhotoUploadApiCall(file)
.subscribeOn(getSchedulerProvider().io())
.observeOn(getSchedulerProvider().ui())
.subscribe(response -> {

Log.d("fileupload", "it is successful" + response);
if (!isViewAttached()) {
return;
}

}, throwable -> {
if (!isViewAttached()) {
return;
}
Log.d("fileupload", "error: ");

getMvpView().hideLoading();

// handle the profile retrieval error here
//getMvpView().showDialog(R.string.unknown_error, R.string.unknown_error_message);

if (throwable instanceof ANError) {
ANError anError = (ANError) throwable;
Log.d("fileupload", "error: " + anError.getErrorCode());

handleApiError(anError);
}
}));

这是我的api调用:
@Override
public Single<JSONObject> updateCurrentUserPhotoUploadApiCall(File file) {
return mApiHelper.doUploadPhoto(mPreferencesHelper.getCurrentUserId(), file);
}

尝试上载图像时,我得到的响应是:fileupload:error:400
而文件路径和一切似乎都是正确的。(文件路径是:
/存储/模拟/0/dcim/15664153315.jpg)
知道我做错了什么吗?
我还尝试了post请求(不使用multipart,只将filepath作为body参数传递,这样:
Rx2ANRequest.PostRequestBuilder post = Rx2AndroidNetworking.post(processUrl(ApiEndPoint.ENDPOINT_UPLOAD_PROFILE_PHOTO)) // Please note : processUrl(ApiEndPoint.ENDPOINT_UPLOAD_PROFILE_PHOTO)) = https://myapps.com/service-profile/v1/member/photo/{userId}
.addHeaders("Authorization", mApiHeader.getFormattedProtectedApiHeader())
.addPathParameter("userId", userId)
.addBodyParameter("photo",filepath.getAbsolutePath());

但没有任何运气。当我将文件作为body参数传递时,它甚至不显示post请求的成功或错误。知道我会错过什么吗?
邮递员按预期工作,它推荐以下的OKHTTP客户端代码,用于Java:
OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");
RequestBody body = RequestBody.create(mediaType, "------WebKitFormBoundary7MA4YWxkTrZ\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"1ab6ef77b355e9acd7cc9b82b5c8ec4f.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--");
Request request = new Request.Builder()
.url("https://myapps.com/api/service-profile/v1/member/photo/9ea899b8-b271-486b-ae64-443a17f06a39")
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.addHeader("Authorization", "Bearer eyJraWQiOiJXZ3NucHRZekZYMnZsRTJ2TEJlUFpjSlJ4TU93SFRqcGkydDZAwdW03bzU5d2xRTFkxUU1HMGg3Iiwic2NwIjpbIm9mZmxpbmVfYWNjZXNzIiwicHJvZmlsZSIsIm9wZW5pZCIsIm1lbWJlciIsImVtYWlsIl0sInN1YiI6InZhcmFuaGErd3BkZXZsYUBjbnZ3cC5jb20iLCJtZW1iZXIucmVhZCI6dHJ1ZSwibWVtYmVyLndyaXRlIjp0cnVlfQ.LQhea6roQyQNIRnb3XWVuQZjoid2yn7TT-cgbdDeUnbMCUtFnOiHKPOLo_zpRr0bB429-yuLeSLdLjj_mF-PESbr0SfvNj01N-AWtYvyn9gEvcqS3hHHzPI44RDYkU8CtenByxwDBLUTlrdAGW7Xmi-UtGdd2_kaM8zkZoVWRS8dbymCVfZyoYr7DeR9hFZtD8RCtYRMRJrgQGZoMv7_1oCJyo8lAWuMpUmZfsEscOOw44hFoNADv221l70mbTIb-XwA")
.addHeader("User-Agent", "PostmanRuntime/7.15.2")
.addHeader("Accept", "*/*")
.addHeader("Cache-Control", "no-cache")
.addHeader("Postman-Token", "3f81374d-d895-4a55-9122-297,3ff3b3f8-7149-46b9-887e-db1b4")
.addHeader("Host", "myapps.com")
.addHeader("Cookie", "AWSALB=HKdluG7WMh8PQmgNrYwRK+fpDEAE3DKnRQXIWOngg7Tn9kzEy5lQWhSsU45P7aLxk7Y")
.addHeader("Accept-Encoding", "gzip, deflate")
.addHeader("Content-Length", "17805")
.addHeader("Connection", "keep-alive")
.addHeader("cache-control", "no-cache")
.build();

Response response = client.newCall(request).execute();

我只是想知道如何理解这篇文章(正文)的内容,从我的设备上传选定的jpg图像?另外,如果有人可以修改我现有的androidnetworking(rx2)代码,使其按照邮递员的建议工作,那将是非常好的。

最佳答案

试试这个。我是根据你的邮递员请求查询来做的,很肯定会成功的。

 OkHttpClient okHttpClient = new OkHttpClient();

MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
builder.addFormDataPart("photo", filepath.getAbsolutePath());

String url = ApiEndPoint.ENDPOINT_UPLOAD_PROFILE_PHOTO;
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), filepath);
builder.addFormDataPart("photo", filepath.getName(), fileBody);
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(processUrl(url))
.addHeader("Authorization",mApiHeader.getFormattedProtectedApiHeader())
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new okhttp3.Callback(){
@Override
public void onFailure(Call call, IOException e) {
Log.e("OkHttp1", "onFailure: "+e.toString());
}

@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody body = response.body();
if (body != null) {
Log.e("OkHttp1", "onResponse: " + body.string());
} else {
Log.e("OkHttp1", "onResponse: null");
}
}
});

关于android - 如何为rxjava2 androidnetworking POST请求传递多部分body参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57598276/

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