【发布时间】:2019-06-09 22:46:09
【问题描述】:
我正在使用改造,我需要上传和图像,但我收到状态代码 400。 这是代码。
这是界面。
public interface SupportInterface {
//Get request for sending photo in chat
@Multipart
@POST("/api/upload-image")
Call<ResponseBody> getChatPhoto(@Header("Content-Type") String json,
@Header("Authorization") String token,
@Header("Cache-Control") String cache,
@Part("type") String type,
@Part("user_id") String userId,
@Part MultipartBody.Part image_path);
}
我正在使用标题 + 我还需要发送 user_id 和类型。所以我使用@Part。我做对了吗?
这是初始化部分的改造。
public class ApiClient {
private static ApiClient instance;
OkHttpClient.Builder client = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS);
client.addInterceptor(new Interceptor() {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
Request request = chain.request();
request = request.newBuilder()
.header("Cache-Control", "public, max-age=0")
.build();
return chain.proceed(request);
}
});
supportopApi = new Retrofit.Builder()
.baseUrl(endpoint)
.client(client.build())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(SupportopApi.class);
}
public Call<ResponseBody> getChatImage(MultipartBody.Part multipartBody) {
return supportopApi.getChatPhoto("application/json", There is my accessToken,
"no-cache", "5", This is userID, multipartBody);
}
}
如果我在这里做错了什么,请告诉我。
这是主要部分。
public void getChatImage() {
File file = new File("/storage/emulated/0/Download/s-l640.jpg");
RequestBody reqFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part multiPartFile = MultipartBody.Part.createFormData("image", file.getName(), reqFile);
Call<ResponseBody> chatImageCall = apiClient.getChatImage(multiPartFile);
chatImageCall.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
Log.d(TAG, response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, "Response is not successful: " + response.errorBody(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "An error occurred", Toast.LENGTH_SHORT).show();
}
});
}
我在这里收到错误的请求 400。
【问题讨论】:
-
@Multipart+Content-Type: application/json...呵呵...好一个...您应该决定一种内容类型,但没有人会帮助您,因为我们不知道后端期望什么 -
我做错了服务器说,我需要设置内容类型multipart/form-data,但它也给了400。
-
然后删除
@Header("Content-Type") json -
如果内容类型是multipart/form-data,所以需要把application/json改成multipart/form-data。
-
所以我需要将 application/json 更改为 multipart/form-data ...不 ...
@Multipart+@POST会处理它
标签: java android retrofit http-status-code-400