Hayk Mkrtchyan
Hayk Mkrtchyan

Reputation: 3255

Retrofit image upload returns bad request 400

I'm using retrofit and I need to upload and image, but I'm getting status code 400. Here's the code.

This is the interface.

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);

}

I'm using headers + I need to send user_id and type too. So I'm using @Part. I done right yes?

Here's the retrofit in initialization 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);
   }
}

If I done here something wrong please tell me.

And here's the main part.

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();
        }
    });
}

I'm getting here bad request 400.

Upvotes: 1

Views: 2145

Answers (1)

Mạnh Quyết Nguyễn
Mạnh Quyết Nguyễn

Reputation: 18235

@Header("Content-Type") String json

You declare your content type is JSON but actually you pass to server the multipart (form data)

So I think you're trying to do:

@Header("Accept") String json

(accept JSON from server)

Upvotes: 2

Related Questions