PostingApi.interface
package com.minui.photo.api;
import com.minui.photo.model.PostRes;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Header;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface PostingApi {
@Multipart
@POST("/posting")
Call<PostRes> addPosting(@Header("Authorization") String token, @Part MultipartBody.Part photo, @Part("content")RequestBody content);
}
multipart를 달고 파라미터는 Part를 단다.
AddActivity.java의 retrofit 보내기 부분
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 = getApplication().getSharedPreferences(Config.PREFERENCE_NAME, MODE_PRIVATE);
String accessToken = sp.getString("accessToken", "");
Call<PostRes> call = api.addPosting("Bearer "+accessToken,
photo,
contentBody);
showProgress("포스팅 업로드 중...");
call.enqueue(new Callback<PostRes>() {
@Override
public void onResponse(Call<PostRes> call, Response<PostRes> response) {
dismissProgress();
Toast.makeText(AddActivity.this, "업로드가 완료되었습니다.", Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void onFailure(Call<PostRes> call, Throwable t) {
dismissProgress();
}
});
주석대로 파일과 텍스트를 보내는 경우로 나눠서 파라미터를 만들고 파라미터 대입해주면 된다.
'안드로이드' 카테고리의 다른 글
안드로이드 구글 맵스 설정 (0) | 2022.07.29 |
---|---|
안드로이드 위치 받아오기 (0) | 2022.07.29 |
안드로이드 Retrofit2 라이브러리를 이용한 POST로 API호출 (0) | 2022.07.21 |
안드로이드 Retrofit2 라이브러리 사용을 위한 설정 방법 (0) | 2022.07.21 |
안드로이드 카메라 설정 (0) | 2022.07.21 |