본문 바로가기

웹 & 앱 꿀 TIP

[android] 내가 겪은 retrofit 오류 및 설명

728x90
반응형

part를 하나만 사용하는데에도 multipart를 사용해야하는 경우가 있더라.

 

retrofit에 대하여 조금의 활용도가 있는 상태라 생각하고 설명하겠다.

 

1. POST

2. GET

3. DELETE

4. PUT

 

1. POST

 

먼저 header에 토큰값을 넣고 사진과 string을 같이 post할 경우엔 이미지와 같은 경우 텍스트와 한 번에 보낼 수 없기 때문에 나누어서 전송한다 

ex) interface

@Multipart
@POST("upload/")
Call<AddCustomerRes> addCustomer(@Header("Authorization") String token,
                                 @Part MultipartBody.Part my_photo,
                                 @Part ("my_photo_title")RequestBody my_photo_title);

 

AddCustomerRes란 서버에서 받는 값을 재정렬하는 java 파일이다 생김새는 이렇다

package com.example.nailmanna;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class AddCustomerRes {

    @SerializedName("user")
    @Expose
    private Integer user;
    @SerializedName("my_photo_title")
    @Expose
    private String my_photo_title;
    @SerializedName("my_photo")
    @Expose
    private String my_photo;
    @SerializedName("id")
    @Expose
    private int id;
    @SerializedName("like_count")
    @Expose
    private int like_count;

    public Integer getUser() {
        return user;
    }

    public void setUser(Integer user) {
        this.user = user;
    }

    public String getMyphototitle() {
        return my_photo_title;
    }

    public void setMyphototitle(String my_photo_title) {
        this.my_photo_title = my_photo_title;
    }

    public String getMyphoto() {
        return my_photo;
    }

    public void setMyphoto(String my_photo) {
        this.my_photo = my_photo;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getLike_count() {
        return like_count;
    }

    public void setLike_count(int like_count) {
        this.like_count = like_count;
    }
}

 

 

위와같은 파일은 내가 활용할 때 아래와 같이 활용하였다.

//String token추가
    public void addCustomer(String token, String my_photo_title){
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://43.200.13.213:8000/like/")
                .addConverterFactory(GsonConverterFactory.create()).build();

        String m_token = "Bearer " + token;
        File file = new File(path);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        // 오류 시 get Name 확인  >  getUser()
        MultipartBody.Part body = MultipartBody.Part.createFormData("my_photo", file.getName(),requestFile);
        // 오류 시 cus_name 의 속성 check
        RequestBody cus_reference = RequestBody.create(MediaType.parse("multipart/form-data"), my_photo_title);

        UserService userService = retrofit.create(UserService.class);

        Call<AddCustomerRes> call = userService.addCustomer(m_token, body, cus_reference);
        Log.e("m_token cheak" , "====="+m_token);
        call.enqueue(new Callback<AddCustomerRes>() {
            @Override
            public void onResponse(Call<AddCustomerRes> call, Response<AddCustomerRes> response) {
                Log.e("response cheak", "======"+response);
                if(response.isSuccessful()){
                    if(response.body().getMyphoto()!= null){
                        Toast.makeText(getApplicationContext(), "등록이 완료 되었습니다.", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(getApplicationContext(),NailnoticeActivity.class);
                        startActivity(intent);
                        Log.e("response check", "======="+response.body());
                    }else{
                        Toast.makeText(getApplicationContext(), "not Added", Toast.LENGTH_SHORT).show();
                        Log.e("log check", "="+response.body());
                    }
                }
            }

            @Override
            public void onFailure(Call<AddCustomerRes> call, Throwable t) {
//                Toast.makeText(getApplicationContext(), t.toString(), Toast.LENGTH_SHORT).show();
                Log.e("response cheak", "======"+t);
                Toast.makeText(getApplicationContext(), "등록이 완료 되었습니다.", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),NailnoticeActivity.class);
                startActivity(intent);
            }
        });
    }

2. GET

get의 경우 서버에 값을 가지고 오는 거 그 이상 이하도 아니기에 get을 할 때 필요한 값만 인수로 넣으면 된다.

에러가 나면 해당 경로가 진정 맞는지 postman을 사용하는 것도 하나의 방법이다.

ex)내가 사용한 get방식 코드 to interface

// 내가 좋아요 한 파일
@GET("mylike/")
Call<List<AddCustomerRes>> LikePhoto (@Header("Authorization") String token);

// 내가 올린 파일
@GET("upload/")
Call<List<AddCustomerRes>> MyUpload (@Header("Authorization") String token);

// 전체
@GET("all/")
Call<List<AddCustomerRes>> PhotoAll(@Header("Authorization") String token);

// 좋아요
@GET("like/{my_photo_title}/")
Call<AddCustomerRes> PhotoLike (@Header("Authorization") String token,
                                @Path ("my_photo_title") String my_photo_title);

 

// 내가 좋아요한 파일
public void LikePhoto(String token){
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://43.200.13.213:8000/like/")
            .addConverterFactory(GsonConverterFactory.create()).build();
    UserService userService = retrofit.create(UserService.class);
    String m_token = "Bearer "+token;
    Call<List<AddCustomerRes>> TestHeader = userService.LikePhoto(m_token);
    Log.e("m_token cheak" , "====="+m_token);
    TestHeader.enqueue(new Callback< List<AddCustomerRes> >() {
        @Override
        public void onResponse(Call<List<AddCustomerRes>> call, Response<List<AddCustomerRes>> response) {
            if( response.isSuccessful() ){
                //정보 담을 배열 생성
                HashMap<String, String> hashMap = new HashMap<>();
                for(int i = 0; i < response.body().size(); i++ ){
                    Log.i("say_","============================================================================");
                    Log.i("say"," [ "+ i + " ] response myphototitle = "+ response.body().get(i).getMyphototitle()  );
                    Log.i("say__"," [ "+ i + " ] response myphoto = "+ response.body().get(i).getMyphoto() );

                    hashMap.put(response.body().get(i).getMyphototitle(), response.body().get(i).getMyphoto());
                }
                commonData.getInstance().SetPhotoLike(hashMap);

                // 정보 세팅
                for(Map.Entry<String, String> i : commonData.getInstance().GetPhotoLike().entrySet() ){
                    Log.i("say", "MylikeTitle = [ "+ i.getKey() +"] Photo = [" + i.getValue() +"] ");
                }

            }else {
                Log.i("say","response nononono "+response.code());
            }
        }

        @Override
        public void onFailure(Call<List<AddCustomerRes>> call, Throwable t) {
            Log.i("say","failure" + t.getMessage());
        }
    });

}

 

 

3. DELETE

나는 유독 put과delete를 할 때 애를 먹었는데, Delect는 다른 레트로핏 통신과 달리 안된단다(왜인지 모름)그래서 http통신을 사용했는데 의외로 사용 방법은 간단했다.

 

// 사진 삭제
@Multipart
@HTTP(method = "DELETE", path = "upload/", hasBody = true)
Call<AddCustomerRes> PhotoDel(@Header("Authorization") String token,
                              @Part ("my_photo_title")RequestBody my_photo_title);

multipart를 사용하지 않아도 될 거같이보였는데 multipart를사용했어야 된것이였다. 

저자가 겪은 일을 겪지 않게 완벽하게 되어보이는 코드에 한번 multipart를 기입해보는 것도 하나의 방법이다. 아니라고생각하지 말고 한번은 해보시길..

ex)활용 코드

// 내가 올린 사진 삭제
public void PhotoDel(String toke, String my_photo_title){
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://43.200.13.213:8000/like/")
            .addConverterFactory(GsonConverterFactory.create()).build();

    String m_token = "Bearer "+toke;
    RequestBody m_my_photo_title = RequestBody.create(MediaType.parse("multipart/form-data"), my_photo_title);

    UserService userService = retrofit.create(UserService.class);
    Call<AddCustomerRes> PhotoDel = userService.PhotoDel(m_token, m_my_photo_title);
    Log.e("m_token cheak photoDel" , "====="+m_token);
    PhotoDel.enqueue(new Callback<AddCustomerRes>() {
        @Override
        public void onResponse(Call<AddCustomerRes> call, Response<AddCustomerRes> response) {
            if( response.isSuccessful() ){
                Log.i("say photo name cheak", ">>>"+ my_photo_title);

            }else {
                Log.i("say","response nononono "+response.code());
            }
        }

        @Override
        public void onFailure(Call<AddCustomerRes> call, Throwable t) {
            Log.i("say","failure" + t.getMessage());
        }
    });

}

 

4. PUT

이또한 multipart때문에 애를 먹었다. path와part인데 왜multipart인것인지.. 내 경우는 path로 해당 값을 넣고, 또 다른 값으로 값을 보내는 것이였는데. 이또한 multipart를 해야했었다.

// 내가 올린 사진 수정
@Multipart
@PUT("like/update/{my_photo_title}/")
Call<AddCustomerRes> PhotoUpdate (@Header("Authorization") String token,
                                  @Path ("my_photo_title") String my_photo_titl,
                                  @Part ("my_photo_title")RequestBody my_photo_title);
// 내가 올린 사진 수정
public void PhotoUpdate(String token, String my_photo_titl, String my_photo_title){
    Retrofit retrofit = new Retrofit.Builder().baseUrl("http://43.200.13.213:8000/")
            .addConverterFactory(GsonConverterFactory.create()).build();

    String m_token = "Bearer "+token;
    RequestBody m_my_photo_title = RequestBody.create(MediaType.parse("multipart/form-data"), my_photo_title);

    UserService userService = retrofit.create(UserService.class);
    Call<AddCustomerRes> PhotoUpdate = userService.PhotoUpdate(m_token, my_photo_titl, m_my_photo_title);
    Log.e("m_token cheak Update" , "====="+m_token);
    PhotoUpdate.enqueue(new Callback<AddCustomerRes>() {
        @Override
        public void onResponse(Call<AddCustomerRes> call, Response<AddCustomerRes> response) {
            if( response.isSuccessful() ){
                Log.i("say photo name cheak", "response Success");

            }else {
                Log.i("say","response nononono "+response.code());
            }
        }

        @Override
        public void onFailure(Call<AddCustomerRes> call, Throwable t) {
            Log.i("say","failure" + t.getMessage());
        }
    });

}

 

 

예시를 보는 것보다 더 나은 교육은 없다 백문이 불여일견..이니 뭐라니..

 

너무 스트레스를 받았어서 이젠 득도를 했다.

 

통신쪽이 제일 까다로운듯 하다.

728x90
반응형