안드로이드 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(); }
'프로그램 > Android' 카테고리의 다른 글
안드로이드 SNS Facebook 로그인 (0) | 2018.11.12 |
---|---|
HttpURLConnection Multipart 파일 업로드 (0) | 2018.08.29 |
이미지사이즈 초과시 대처(Bitmap too large) (0) | 2018.01.11 |
안드로이드 Fabric 설치 (0) | 2017.11.17 |
안드로이드 Url을 이용하여 Bitmap 다운로드 (0) | 2017.11.09 |