네트워크 통신
※ 네트워크 통신을 하기위서는 처음에 AndroidMainfest.xml 파일에서 인터넷 설정이 필요하다


빨간색으로 밑줄친 부분을 추가해주면된다.
<uses-permission android:name="android.permission.INTERNET" />
--> 민감한 권한 설정
android:usesCleartextTraffic="true"
--> 모든 Http URL에 대해서 접근 허용
노란색으로 동그라미된 부분을 바꿔주면

여기 맨 윗부분의 라벨을 바꿀수 있다.
· 네트워크 통신 화면 코드
<?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=".WifiActivity">
<EditText
android:id="@+id/etWifi"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="http://"
app:layout_constraintEnd_toStartOf="@+id/btnWifi"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnWifi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="요청"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvWifi"
android:layout_width="0dp"
android:layout_height="0dp"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btnWifi" />
</androidx.constraintlayout.widget.ConstraintLayout>


네트워크 화면의 ID : - etWifi: 주소 입력창
- btnWifi: 주소를 입력한 후 그 주소로 이동하게 하는 버튼
- tvWifi: 그 주소의 내용을 보여주는 텍스트 뷰창
※ 네트워크 통신!!! Volley 라이브러리
- 가장 많이 사용하는 Volley 라이브러리
- 안드로이드 내장 라이브러리 X
- 외부 라이브러리!!
- build.gradle 안에 dependencies에
- 라이브러리 주소를 추가해도 되고
- 혹은 직접 검색 후 추가!!
- File -> Project Structure -> Dependencies -> '+' 누른 후 -> Library dependency





- Gradle Scripts의 2번째 build gradle에서 -> dependencies의
- implementation 'com.android.volley:volley:1.2.1' 확인
● 네트워크 Activity 소스코드
package com.example.ex221004;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.ex221004.databinding.ActivityWifiBinding;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class WifiActivity extends AppCompatActivity {
ActivityWifiBinding binding;
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityWifiBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// 네트워크 통신
// Permission(권한)
// 2. RequestQueue 객체 생성
if(requestQueue == null){
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
// etWifi를 빈문자열로
binding.etWifi.setText("");
binding.btnWifi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url = binding.etWifi.getText().toString();
String rank = binding.etWifi.getText().toString();
String url2 = "https://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20221004";
StringRequest request = new StringRequest(
Request.Method.GET,
url2,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// 응답 성공시
binding.tvWifi.setText(response);
try {
int c_rank =Integer.parseInt(rank);
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonObject2 = jsonObject.getJSONObject("boxOfficeResult");
JSONArray movies = jsonObject2.getJSONArray("dailyBoxOfficeList");
JSONObject movie = (JSONObject)movies.get(c_rank-1);
String movieNm = movie.getString("movieNm");
binding.tvWifi.setText((c_rank +"위영화 :"+ movieNm));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// 응답 실패시
}
}
);
// 4. RequestQueue에 Request추가!!
requestQueue.add(request);
}
});
}
}
※ 에뮬레이터 실행안될시 리셋 방법


- 내 실행중인 프로젝트명 안드로이드 앱 클릭
- 가운데 설치제거 누르기




2022.10.04 영화진흥위원회 영화 순위 오픈api =
네트워크 통신 4단계
0. Internet 권한 부여!! (AndroidManifest.xml)
1. Volley 라이브러리 추가
2. RequestQueue 객체 생성
3. Request 객체 생성: StringRequest
4. RequestQueue에 Request추가!!
- RequestQueue 객체 생성
requestQueue 가 null일때,
if(requestQueue == null){
requestQueue = Volley.newRequestQueue(getApplicationContext()); # 페이지 정보 반환
}
- String url = binding.etWifi.getText().toString(); # etwifi의 텍스트를 url에 저장
String rank = binding.etWifi.getText().toString(); # 검색할 영화 랭크를 rank에 저장
String url2 = "https://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/searchDailyBoxOfficeList.json?key=f5eef3421c602c6cb7ea224104795888&targetDt=20221004"; # url2에 22.10.04 영화진흥위원회 사이트 저장

- method-> GET or POST 방식 결정, url -> 이동할 url, listener -> 응답성공시, errorListener ->응답 실패시
- StringRequest request = new StringRequest(
Request.Method.GET, # GET or POST 방식 결정
url2, # 이동할 url
new Response.Listener<String>() { # 응답 성공했을때
@Override
public void onResponse(String response) {
// 응답 성공시
binding.tvWifi.setText(response); # 텍스트 뷰에 응답된 내용을 표시함
try {
// 문자열 rank -> 정수형 값으로 변환
int c_rank =Integer.parseInt(rank);

JSONObject jsonObject = new JSONObject(response);
JSONObject jsonObject2 = jsonObject.getJSONObject("boxOfficeResult"); # object로 받아서
JSONArray movies = jsonObject2.getJSONArray("dailyBoxOfficeList"); # 배열 받아서
JSONObject movie = (JSONObject)movies.get(c_rank-1);
String movieNm = movie.getString("movieNm");
binding.tvWifi.setText((c_rank +"위영화 :"+ movieNm));
// Java에서는 자료형이 달라도 연산이 가능->자동으로 형변환됌. c_rank: int -> string
} catch (JSONException e) {
e.printStackTrace(); # 예외 발생시 예외 관련 원인 문구를 출력해 줌
}
}
}
- new Response.ErrorListener() { # 응답 실패했을때
@Override
public void onErrorResponse(VolleyError error) {
// 응답 실패시
}}
- RequestQueue에 Request추가!!
requestQueue.add(request);
※ Java 예외 처리
try{실행문장;}
catch(ExceptionClass e){에러 발생 시 실행 로직;}
compile 이후 발견되는 에러 관련
try~catch구문을 사용해야 하고
이 때 발생되는 에러는
에러클래스명을 명시.
e.printStackTrace();
-> 예외 발생시 예외 관련 원인 문구를 출력해 줌
'개발 공부 > 안드로이드 스튜디오(코틀린)' 카테고리의 다른 글
안드로이드 스튜디오(Web 뷰) (0) | 2023.10.18 |
---|---|
안드로이드 스튜디오(로그인 + 플라스크서버) (0) | 2023.10.18 |
코틀린 람다식 함수 (1) | 2023.10.18 |
안드로이드 스튜디오(문자열 배열, 게시판에 게시글 추가/삭제) (0) | 2023.10.18 |
안드로이드 스튜디오(새로운 프로젝트 만들기, ViewBinding 사용법) (0) | 2023.10.18 |