본문 바로가기

Android/Basic

[Android] Volley 라이브러리를 활용한 서버 통신

웹페이지에 그냥 요청해서 html 형식으로 불러와 텍스트뷰에 뿌려보는 예제.


0. Volley 라이브러리 추가

implementation 'com.android.volley:volley:1.1.0'


1. 인터넷 권한 추가

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


2. xml 레이아웃 작성

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="요청하기" />

<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_orange_dark">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:text="textView"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</ScrollView>
</LinearLayout>


3. Helper 클래스 작성

 * Volley는 RequestQueue 객체로 서버 연결을 제어하는데, 이 객체는 애플리케이션에서 하나만 만들어지도록 하기 위해 별도의 클래스에 static 멤버로 선언. -> 싱글톤 패턴에 맞추면 더 좋을듯 하다.

public class AppHelper {
public static RequestQueue requestQueue;
}


4. 메인 액티비티 클래스 작성

public class MainActivity extends AppCompatActivity {
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = findViewById(R.id.textView);

findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendRequest();
}
});

if(AppHelper.requestQueue == null)
AppHelper.requestQueue = Volley.newRequestQueue(getApplicationContext());
}

public void sendRequest(){
String url = "http://www.google.co.kr";

StringRequest request = new StringRequest(
Request.Method.GET,
url,
new Response.Listener<String>() { // 정상 응답
@Override
public void onResponse(String response) {
println("응답 -> "+response);
}
},
new Response.ErrorListener() { // 에러 발생
@Override
public void onErrorResponse(VolleyError error) {
println("에러 -> "+error.getMessage());
}
}

){ // Post 방식으로 body에 요청 파라미터를 넣어 전달하고 싶을 경우
// 만약 헤더를 한 줄 추가하고 싶다면 getHeaders() override
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parmas = new HashMap<String, String>();

return parmas;
}
};

// 요청 객체를 만들었으니 이제 requestQueue 객체에 추가하면 됨.
// Volley는 이전 결과를 캐싱하므로, 같은 결과가 있으면 그대로 보여줌
// 하지만 아래 메소드를 false로 set하면 이전 결과가 있더라도 새로 요청해서 응답을 보여줌.
request.setShouldCache(false);
AppHelper.requestQueue.add(request);
println("요청 보냄.");
}

public void println(String data){
textView.append(data+"\n");
}
}

* StringRequest 생성자 파라미터 설명

Request.Method.GET : int // 요청 방식. POST도 가능

url : String // 접속할 웹서버의 url 주소

Response.Listener<String>// 응답을 성공적으로 받았을 경우 onResponse를 호출하는 리스너 객체

Response.ErrorListener // 에러가 발생했을 때 호출되는 리스너 객체

'Android > Basic' 카테고리의 다른 글

[Android] 웹에서 Image 다운로드  (0) 2018.07.09
[Android] Gson을 이용한 JSON 변환  (0) 2018.07.07
[Android] HttpURLConnection 예제  (0) 2018.07.07
[Android] Socket 통신 예제  (0) 2018.07.07
[Android] AsyncTask  (0) 2018.07.06