개발/Android

[안드로이드] Retrofit을 이용하여 node.js 통신하기 (1)

Eun 2021. 9. 4. 17:27

졸업작품을 하면서 초반에는 volley를 이용해서 통신을 하였으나 Retrofit이라는 것을 알게 되었다.

Volley보다는 Retrofit을 많이 이용한다고 하여 한번 사용해보고 싶었다. 

 

나는 투표 애플리케이션을 제작하고 있었기에, 투표 버튼을 누르면 정보(placeid, candidateid, UserNumber)가 넘어가게끔 구현하였다.

 

1. 우선 '투표하기' 버튼을 만들어 주었다.

 

  • activity_vote.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CandidateListActivity">

    <Button
        android:id="@+id/btn_vote"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="투표 하기" />

</androidx.constraintlayout.widget.ConstraintLayout>

2. gradle에 retrofit을 추가

 //retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    implementation 'com.squareup.retrofit2:converter-scalars:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'

위에 코드를 삽입하고 Sync now를 눌러주었다.

 

3. AndroidManifest에 권한 추가

 

아래 코드를 <manifest...> 코드 안에다 삽입하였고 

<uses-permission android:name="android.permission.INTERNET" />

아래 코드는 <application> 코드 안에다 삽입해주었다.

android:usesCleartextTraffic="true"

위에 코드는 인터넷 통신을 위한 코드이다. 

 

4. 인터페이스 생성

 

이제 인터페이스를 생성해야하는데 내가 생성한 파일은 총 3개이다.

  • ApiInterface.java
  • ApiClient.java
  • Vote.java (데이터 클래스)

ApiInterface.java

public interface ApiInterface {

    @GET("/app/setVote")
    Call<Vote> getVote(@Query("placeid") String placeid, @Query("candidateid") int candidateid, @Query("UserNumber") String UserNumber );


}

여기서 @GET은 Query 형태로 보내는 어노테이션이다. 

placeid와 candidateid와 UserNumber를 보내는 형태.

 

ApiClient.java

public class ApiClient {

    private static final String URL = "http://주소:포트번호/";
    private static Retrofit retrofit;

    public static Retrofit getApiClient(){
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        if (retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build();
        }

        return retrofit;
    }
}

Retrofit은 싱글턴 패턴을 이용하기때문에 ApiClient를 하나 만들고 계속 가져다 쓰는 방식이다. 

 

MainActivity.java




public class VoteActivity extends AppCompatActivity {

    //retrofit
    private ApiInterface service;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vote);

        voting();

	}
    
    public void voting() {


        // 레트로핏 연결
        service = ApiClient.getApiClient().create(ApiInterface.class);

        Button btn_vote = (Button) findViewById(R.id.btn_vote);
        btn_vote.setOnClickListener (new View.OnClickListener(){

            @Override
            public void onClick(View v){

                Call<Vote> call_get = service.getVote(placeid, candidateNumber, UserNumber);
                call_get.enqueue(new Callback<Vote>() {
                    @Override
                    public void onResponse(Call<Vote> call, retrofit2.Response<Vote> response) {
                        //성공했을 경우
                        if (response.isSuccessful()) {//응답을 잘 받은 경우
                            String result = response.body().toString();
                            System.out.println("투표 성공~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
                        } else {    //통신은 성공했지만 응답에 문제있는 경우
                            System.out.println("error="+String.valueOf(response.code()));
                            Toast.makeText(getApplicationContext(), "error = " + String.valueOf(response.code()), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Vote> call, Throwable t) {//통신 자체 실패
                        Toast.makeText(getApplicationContext(), "Response Fail", Toast.LENGTH_SHORT).show();
                    }
                  });
                }
        });
}

Vote.java


public class Vote {

    String placeid;
    int candidateNumber;
    String UserNumber;

    public String getPlaceid() {
        return placeid;
    }

    public void setPlaceid(String placeid){
        this.placeid = placeid;
    }

    public int getCandidateNumber() {return candidateNumber;}

    public void setCandidateNumber(int candidateNumber) {this.candidateNumber=candidateNumber;}

    public String getUserNumber() {return UserNumber;}

    public void setUserNumber(String UserNumber) {
        this.UserNumber=UserNumber;
    }
}

여기까지 앱에서 동작하는 부분이다. 다음 포스팅은 node.js를 다뤄볼 예정이다. 

 


- 참고