개발일지

[android][JAVA][Kotlin] HttpUrlConnection 를 이용한 HTTP 통신 본문

Android

[android][JAVA][Kotlin] HttpUrlConnection 를 이용한 HTTP 통신

강강강 2021. 12. 10. 09:33
try {
    val url = URL(URL)  // 1. URL 객체 생성
    val postconn = url!!.openConnection() as HttpURLConnection // 2. URL 연결
    postconn.requestMethod = "POST" // 3. 요청방식 설정
    postconn.setRequestProperty("Content-type", "application/json") // 4. 서버 Response Data 를 json 형식의 타입으로 요청
    postconn.doOutput = true // 5. OutputStream 으로 POST 데이터를 넘겨주겠다는 옵션
    var os: OutputStream = postconn.outputStream
    os.write(body.toString().toByteArray()) // 매개변수인 바이트배열의 모든 바이트를 outputstream 으로 보냄
    os.flush() // 버퍼에 남아있을 수 있는 잔류데이터 모두 출력 
    os.close() // 사용한 시스템 자원 풀어줌

    if (postconn.responseCode == HttpURLConnection.HTTP_CREATED) {
        do {
            if (isCancelled) {
                return cancelObj
            }
            val url = URL("$URL" + params[0])
            val getconn = url!!.openConnection() as HttpURLConnection
            getconn.requestMethod = "GET"
            getconn.setRequestProperty("Content-type", "application/json")
            getconn.doInput = true


			// 실제 서버로 Request 요청하는 부분 (getconn.responseCode)
            if (getconn.responseCode == HttpURLConnection.HTTP_OK) {
                var tmp = InputStreamReader(getconn.inputStream, "UTF-8")
                var reader = BufferedReader(tmp)
                var line: String = reader.readLine()
                output = JSONObject(line)

                if (output.getString("STATUS") == "DONE") {
                    return output.toString()
                }
                Thread.sleep(1000)
            } else {
                throw error("Not HTTP status code 200, Current status: " + getconn.responseCode)
            }
        } while (true)
    } else {
        throw error("Not HTTP status code 201, Current status: " + postconn.responseCode)
    }
} catch (e: Exception) {
    e.printStackTrace()
    Log.e("Exception", e.message)
}

// HttpURLConnection 객체 생성.

HttpURLConnection conn = null;

 

// URL 연결 (웹페이지 URL 연결.)

conn = (HttpURLConnection)url.openConnection();

 

// TimeOut 시간 (서버 접속시 연결 시간)

conn.setConnectTimeout(CONN_TIMEOUT * 1000);

 

// TimeOut 시간 (Read시 연결 시간)

conn.setReadTimeout(READ_TIMEOUT * 1000);

 

// 요청 방식 선택 (GET, POST)

conn.setRequestMethod(GET);

 

// Request Header값 셋팅 setRequestProperty(String key, String value)

conn.setRequestProperty("NAME", "name");

conn.setRequestProperty("MDN", "mdn");

conn.setRequestProperty("APPID", "appid");

 

// 서버 Response Data를 xml 형식의 타입으로 요청.

conn.setRequestProperty("Accept", "application/xml");

 

// 서버 Response Data를 JSON 형식의 타입으로 요청.

conn.setRequestProperty("Accept", "application/json");

 

// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 text/html로 서버에 전달.)

conn.setRequestProperty("Content-Type", "text/html");

 

// 타입설정(text/html) 형식으로 전송 (Request Body 전달시 application/xml로 서버에 전달.)

conn.setRequestProperty("Content-Type", "application/xml");

 

// 타입설정(application/json) 형식으로 전송 (Request Body 전달시 application/json로 서버에 전달.)

conn.setRequestProperty("Content-Type", "application/json");

 

// 컨트롤 캐쉬 설정

conn.setRequestProperty("Cache-Control","no-cache");

 

// 타입길이 설정(Request Body 전달시 Data Type의 길이를 정함.)

conn.setRequestProperty("Content-Length", "length")

 

// User-Agent 값 설정

conn.setRequestProperty("User-Agent", "test");

 

// OutputStream으로 POST 데이터를 넘겨주겠다는 옵션.

conn.setDoOutput(true);

 

// InputStream으로 서버로 부터 응답을 받겠다는 옵션.

conn.setDoInput(true);

 

// Request Body에 Data를 담기위해 OutputStream 객체를 생성.

OutputStream os = conn.getOutputStream();

 

// Request Body에 Data 셋팅.

os.write(body.getBytes("euc-kr"));

 

// Request Body에 Data 입력.

os.flush();

 

// OutputStream 종료.

os.close();

 

// 실제 서버로 Request 요청 하는 부분. (응답 코드를 받는다. 200 성공, 나머지 에러)

int responseCode = conn.getResponseCode();

 

// 접속해지

conn.disconnect();

'Android' 카테고리의 다른 글

[Android] Gradle dependencies  (0) 2021.12.29
[Android] AsyncTask  (0) 2021.07.06
[Android] Glide Library 글라이드 라이브러리  (0) 2021.07.06
[Android] recyclerview  (0) 2021.06.29
[Android] AAB; Android App Bundle  (0) 2021.06.29