我一直在尝试使用Retrofit,okHttp,Gson和RxAndroid发送包含user_id
等参数的图像文件。
问题是我总是得到以下错误:
500内部服务器错误
我无法将文件上传到服务器。我应该改变什么?
这是我的代码。
HomeActivity.java
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(Date.class, new DateTypeAdapter())
.excludeFieldsWithoutExposeAnnotation()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
UserApi uApi = retrofit.create(UserApi.class);
File file = new File("sdcard/DCIM/Camera/IMG_20131129_123723.jpg");
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
Map<String, Object> map = new HashMap<>();
map.put("user_id", /*some String*/);
map.put("tweet_id", /*some Numbers*/);
map.put("tweet_type", /*some Numbers*/);
this.subscription = uApi.postImage(map, fileBody)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<Tweet>() {
@Override
public void onNext(Tweet tweet) {}
@Override
public void onCompleted() {}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
});
UserApi.java
@Headers("Content-Type: multipart/form-data")
@Multipart
@POST("static/write.json")
public Observable<Tweet> postImage(
@Part("params") Map map,
@Part("file\";filename=\"IMG_20131129_123723.jpg") RequestBody file
);
我还试图自己将标题添加到请求中,但它没有工作,我得到的错误与以前一样。
MultipartBody mb = new MultipartBody.Builder("boundary")
.addPart(Headers.of("Content-Disposition","file; filename=\"IMG_20131129_123723.jpg\"; name=\"IMG_20131129_123723.jpg\""), uploadFile)
.addPart(paramsBody)
.build();
Request request = new Request.Builder()
.url("")
.post(mb)
.build();
的build.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.google.code.gson:gson:2.4'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta3'
compile 'com.squareup.okhttp3:okhttp:3.0.0'
compile 'io.reactivex:rxandroid:0.24.0'
compile 'io.reactivex:rxjava:1.1.0'
}
有人可以帮助我吗?