AsyncTask 를 사용하여 그 안에서 웹 요청을 하고
끝나고 나면 onPostExecute 함수 안에서 UI 수정등을 수행하도록 한다.
예제 코드 (Example)
private void sendMsgBackground() { new AsyncTask() { @Override protected String doInBackground(Void... params) { String msg = ""; try { msg = sendMsg(); } catch (Exception e) { } return msg; } @Override protected void onPostExecute(String msg) { } }.execute(null, null, null); } private void sendMsg() { HttpURLConnection urlConnection = null; try { URL url = new URL("http://mywebsite"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); String urlParameters = "param1=paramVal1"; urlParameters = urlParameters +"&¶m2=paramVal2"; DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8")); writer.write(urlParameters); writer.close(); wr.close(); int responseCode = urlConnection.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { //TODO: exception handling } finally { urlConnection.disconnect(); } }
댓글 없음:
댓글 쓰기