프로그램/Android

HttpURLConnection Sample(Get, Post)

잡식성초보 2018. 8. 27. 22:00

안드로이드 HttpURLConnection Sample입니다.



안드로이드 앱내에서 RestAPI 이용하여 데이터를 받아오기 위한 통신입니다.



기본적인 Get/Post 샘플입니다.


1. GET 통신



private void HttpGet(){

        new AsyncTask<Void, Void, JSONObject>(){

            @Override
            protected JSONObject doInBackground(Void... voids) {

                JSONObject result = null;
                try{
                    URL url = new URL("요청 URL");
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setRequestProperty("content-type", "application/json");
                    connection.setRequestMethod("GET");         // 통신방식
                    connection.setDoInput(true);                // 읽기모드 지정
                    connection.setUseCaches(false);             // 캐싱데이터를 받을지 안받을지
                    connection.setConnectTimeout(15000);        // 통신 타임아웃

                    int responseCode = connection.getResponseCode();

                    if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) {
                        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                        String inputLine;
                        StringBuffer response = new StringBuffer();
                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();

                    } else {
                        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                        String inputLine;
                        StringBuffer response = new StringBuffer();
                        while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                        }
                        in.close();
                    }

                } catch (ConnectException e) {
                    Log.e(TAG, "ConnectException");
                    e.printStackTrace();


                } catch (Exception e){
                    e.printStackTrace();
                }

                return result;
            }

            @Override
            protected void onPostExecute(JSONObject jsonObject) {
                super.onPostExecute(jsonObject);
            }

        }.execute();
    }




2. POST 통신




private void HttpPost(){ new AsyncTask<Void, Void, JSONObject>(){ @Override protected JSONObject doInBackground(Void... voids) { JSONObject result = null; try{ URL url = new URL("요청 URL"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("content-type", "application/x-www-form-urlencoded"); connection.setRequestMethod("POST"); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setConnectTimeout(15000); OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); HashMap<String, String> map = new HashMap<>(); map.put("키값","데이터값");

StringBuffer sbParams = new StringBuffer();


boolean isAnd = false;

for(String key: map.keySet()){

if(isAnd)

sbParams.append("&");


sbParams.append(key).append("=").append(map.get(key));

if(!isAnd)

if(map.size() >= 2)

isAnd = true;

}


wr.wrtie(sbParams.toString());

wr.flush();

wr.close();

int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } else { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); result = new JSONObject(response.toString()); } } catch (ConnectException e) { Log.e(TAG, "ConnectException"); e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } return result; } @Override protected void onPostExecute(JSONObject jsonObject) { super.onPostExecute(jsonObject); } }.execute(); }


반응형