본문 바로가기
Android Studio

[Android Studio] Retrofit으로 API호출할때 form-data 처리하기

by coding_su 2023. 2. 14.

📝Retrofit으로 API호출할때 form-data 처리하기

Retrofit 라이브러리를 이용해 API를 호출할때

Body에 Json이 아닌 form-data로 데이터를 보내야할때 Multipart를 사용한다

 

우선 api를 호출할 interface를 만들어준다

아래 이미지처럼 photo라는 파일 데이터와 content라는 텍스트 파일을 보낼 것이다

public interface PostingApi {

    // 포스팅 생성API
    @Multipart
    @POST("/posting")
    Call<Res> addPosting(@Header("Authorization") String token,
                         @Part MultipartBody.Part photo,
                         @Part("content")RequestBody content);
}

 

아래 코드처럼 만든 api interface를 호출해 사용

Retrofit retrofit = NetworkClient.getRetrofitClient(AddActivity.this);
PostingApi api = retrofit.create(PostingApi.class);

// 멀티파트로 파일을 보내는 경우 파일 파라미터를 만든다
RequestBody fileBody = RequestBody.create(photoFile, MediaType.parse("image/*"));
MultipartBody.Part photo = MultipartBody.Part.createFormData("photo", photoFile.getName(), fileBody);

// 멀티파트로 텍스트를 보내는 경우 텍스트 파라미터 만든다
RequestBody contentBody = RequestBody.create(content, MediaType.parse("text/plain"));

// 헤더에 들어갈 억세스토큰 가져온다
SharedPreferences sp = getSharedPreferences(Config.PREFERENCE_NAME, MODE_PRIVATE);
String accessToken = "Bearer " + sp.getString(Config.ACCESS_TOKEN, "");

Call<Res> call = api.addPosting(accessToken, photo, contentBody);

call.enqueue(new Callback<Res>() {
    @Override
    public void onResponse(Call<Res> call, Response<Res> response) {
        dismissProgress();

        if(response.isSuccessful()){

            finish();

        } else {

        }

    }

    @Override
    public void onFailure(Call<Res> call, Throwable t) {
        dismissProgress();
    }
});

댓글