我需要将图像文件上传到服务器。当前代码
File body = ...
Properties headers = getDefaultHeaders();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(convertToURL(command).toString());
if (headers != null) {
for (Map.Entry<Object, Object> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey().toString(), entry.getValue().toString());
}
}
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(body, "image/jpeg");
mpEntity.addPart("file", cbFile);
httpPost.setEntity(mpEntity);
HttpResponse response = httpClient.execute(httpPost);
String entityString = EntityUtils.toString(response.getEntity());
return new Gson().fromJson(entityString, new TypeToken<Slide>() {}.getType());
我想做同样的事情,使用改造,但是有一些问题。
我的界面:
@Multipart
@POST(COMMAND_ADD_SLIDE)
Call<Slide> addSlide (@PartMap Map<String, RequestBody> params);
代码:
File body = ...
Map<String, RequestBody> map = new HashMap<>();
RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), body);
map.put("file", fileBody);
Call<Slide> call = getApiService(true).addSlide(map);
服务创建代码:
getApiService(boolean isMedia) {
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder builder = original.newBuilder();
builder....//add default headers
.header(Fields.CONTENT_TYPE, isMedia? "multipart/form-data" : "text/json");
Request request = builder
.method(original.method(), original.body())
.build();
return chain.proceed(request);
}
});
OkHttpClient client = httpClient.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(SERVICE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit.create(ApiService.class);
}
获得错误的请求结果。我在哪里做错了?
非媒体类型(JSON)的其他请求正常工作。