안드로이드에서 웹사이트와 텍스트 다운받기

Soomin Kim·2023년 3월 17일

Android

목록 보기
8/14
<manifest ..>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    
    <application
    	android:usesCleartextTraffic="true"
        ...
        >
// MainActivity.kt
// 비동기 클래스가 될 이너 클래스 필요

override fun onCreate(savedInstanceState: Bundle?){
	CallAPILoginAsyncTask().execute()
}

private inner class CallAPILoginAsyncTask(): AsyncTask<Any, Void, String>(){
	private lateinit var customProgressDialog: Dialog
    
    // 백그라운드에서 무언가 시작되거나 인터넷에 연결되기 바로 직전에 실행
    override fun onPreExecute() {
    	super.onPreExecute()
        showProgressDialog()
    }
    
    override fun doInBackground(vararg params: Any?): String{
    	var result: String
        var connection: HttpURLConnection? = null
        
        try{
        	val url = URL("데이터 가져올 api URL")
            connection = url.openConnection() as HttpURLConnection
            // doInput: 데이터 가져오느냐
            connection.doInput = true
            // doOutput: 데이터 송출하냐
            connection.doOutput = true
            
            val httpResult: Int = connection.responseCode
            
            if (httpResult == HttpURLConnection.HTTP_OK){
            	val inputStream = connection.inputStream
                val readr = BufferedReader(inputStream)
                var line: String?
                try {
                	while(reader,readLine().also {
                    line = it} != null) {
                    stringBuilder.append(line + "`n")
                    }
                catch(e: IOExeption)
                e.printStackTrace()
                 
                }finally{
                	try{
                    inputStream.close()
                    }catch(e: iOExeption)
                    e.printStackTrace()
                }
                
                
                result = stringBuilder.toString()
            }else{
            	result = connection.responseMessage
            }
        }catch(e:SocketTimeoutException){
        	result = "Connection Timeout"
        }catch(e:Exception){
        	result = "Error: " + e.message
        }finally{
        	conneciton?.disconnect()
        }
            
         
        }return result
    }
    
    override fun onPostExecute(result: String?) {
    	super.onPostExecute(result)
        cancelProgressDialog()
        
        Log.i("JSON RESPNSE RESULT", result)
        
        val jsonObject = JSONObject(result)
        // key값으로 String 가져오는 것
        val message = jsonObject.optString("message")
        // Int
        val id = jsonOBject.optInt("id")
        // Object
        val profileDetailsObject = jsonObject.optJSONObject("profile_data")
        val isProfileCompleted = profileDetailsObject.optBoolean("is_profile_completed")
        // List
        val dataListArray = jsonObject.optJSONArray("data_list")
        // 사이즈: dataListArray.length()
        // 모든 요소에 접근
        for(item in 0 until dataListArray.length()){
        	Log.i("Value $item", "$dataListArray[item]}")
            val dataItemObject: JSONObject = dataListArray[item] as JSONObject
          	val data_id: Int = dataItemObject.optInt("id")  
        }

POST

CallAPILoginAsyncTask("soomin", 12345).execute()

private inner class CallAPILoginAsyncTask(val username: String, val password: Int) {
...
connection.requestMethod = "POST"

                /**
                 * Sets the general request property. If a property with the key already
                 * exists, overwrite its value with the new value.
                 */
                connection.setRequestProperty("Content-Type", "application/json")
                connection.setRequestProperty("charset", "utf-8")
                connection.setRequestProperty("Accept", "application/json")

                /**
                 * Some protocols do caching of documents.  Occasionally, it is important
                 * to be able to "tunnel through" and ignore the caches (e.g., the
                 * "reload" button in a browser).  If the UseCaches flag on a connection
                 * is true, the connection is allowed to use whatever caches it can.
                 *  If false, caches are to be ignored.
                 *  The default value comes from DefaultUseCaches, which defaults to
                 * true.
                 */
                connection.useCaches = false

                /**
                 * Creates a new data output stream to write data to the specified
                 * underlying output stream. The counter written is set to zero.
                 */
                val wr = DataOutputStream(connection.outputStream)

                // Create JSONObject Request
                val jsonRequest = JSONObject()
                jsonRequest.put("username", username) // Request Parameter 1
                jsonRequest.put("password", password) // Request Parameter 2
                wr.writeBytes(jsonRequest.toString())
                wr.flush() // Flushes this data output stream.
                wr.close() // Closes this output stream and releases any system resources associated with the stream

}
profile
개발자지망생

0개의 댓글