반응형
출처: http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post
원래 NameValuePair를 사용하면 해결되는 문제였으나,
API 22부터 위와 관련된 메소드는 deprecated 되었다.
그래서 가급적이면 이를 사용하지 않는 방법으로 하고 싶었다.
위 링크의 두 번째 대답을 참고하여 사용할 수 있었다.
// 매개변수를 웹으로 보내고 그 결과를 반환하는 함수 // 참고: http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post private String send(HashMap<String, String> map, String addr) { String response = ""; // DB 서버의 응답을 담는 변수 try { URL url = new URL(addr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 해당 URL에 연결 conn.setConnectTimeout(10000); // 타임아웃: 10초 conn.setUseCaches(false); // 캐시 사용 안 함 conn.setRequestMethod("POST"); // POST로 연결 conn.setDoInput(true); conn.setDoOutput(true); if (map != null) { // 웹 서버로 보낼 매개변수가 있는 경우우 OutputStream os = conn.getOutputStream(); // 서버로 보내기 위한 출력 스트림 BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); // UTF-8로 전송 bw.write(getPostString(map)); // 매개변수 전송 bw.flush(); bw.close(); os.close(); } if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { // 연결에 성공한 경우 String line; BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); // 서버의 응답을 읽기 위한 입력 스트림 while ((line = br.readLine()) != null) // 서버의 응답을 읽어옴 response += line; } conn.disconnect(); } catch (MalformedURLException me) { me.printStackTrace(); return me.toString(); } catch (Exception e) { e.printStackTrace(); return e.toString(); } return response; } // 매개변수를 URL에 붙이는 함수 // 참고: http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post private String getPostString(HashMap<String, String> map) { StringBuilder result = new StringBuilder(); boolean first = true; // 첫 번째 매개변수 여부 for (Map.Entry<String, String> entry : map.entrySet()) { if (first) first = false; else // 첫 번째 매개변수가 아닌 경우엔 앞에 &를 붙임 result.append("&"); try { // UTF-8로 주소에 키와 값을 붙임 result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } catch (UnsupportedEncodingException ue) { ue.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return result.toString(); }
반응형