Android

[Android] GLSurfaceView 캡처 → Bitmap → JPEG 변환 후, Retrofit2 post 이미지 전송(2)

EnvEng10 2020. 10. 19. 10:09
반응형

3. 앞서서 얻은 FILE 을  Retrofit2 를 사용하여 서버에 POST 해보자

public class ApiClient {
    public static Retrofit getClient() {
        retrofit = new Retrofit.Builder()
                .baseUrl("URL")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit;
    }
}

public interface ApiService {
    @Multipart
    @POST("endPoint")
    Call<ImageResponse> postImage(@Part("id") RequestBody id,
                                  @Part MultipartBody.Part image);
}

public class ImageResponse {

    private String error;
    private String message;
    
    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
    
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

 

@Part 어노테이션을 이용해 body 에 담기는 인자를 전달해주자.

private void postImage() {
    RequestBody id = RequestBody.create(MediapartBody.FORM, "id");
    RequestBody imageBody = RequestBody.create(MediaType.parse("image/*"), file); // file 을 여기에 넣는다
    MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);
    
    ApiService apiService = ApiClient.getClient().create(ApiService.class);
    apiService.postImage(id, imageBody).enqueue(new Callback<ImageResponse>() {
        @Override
        public void onResponse(Call<ImageResponse> call, Response<ImageResponse> response) {
            if(response.body() != null) {
                Log.d(TAG, "onResponse: " + response.body.getMessage());
            }
        }
        @Override
        public void onFailure(Call<ImageResponse> call, Throwable t) {
            Log.d(TAG, "onFailure: " + t.toString());
        }
   });
}

 

참고 - Stack Overflow

 

 

반응형