Press "Enter" to skip to content

Android에서 JSON 데이터를 송수신

Android에서 JSON 데이터를 송수신하기 위해서 HttpURLConnection을 사용하여 만든 함수 입니다.

  • serverURL : JSON 요청을 받는 서버의 URL
  • postPara : POST 방식으로 전달될 입력 데이터
  • flagEncoding : postPara 데이터의 URLEncoding 적용 여부
  • 반환 데이터 : 서버에서 전달된 JSON 데이터
public static String getJson(String serverUrl, String postPara, boolean flagEncoding) throws Exception {
         URL url = null;
         HttpURLConnection conn = null;
         PrintWriter postReq = null;
         BufferedReader postRes = null;
         StringBuilder json = null;
         String line = null;

json = new StringBuilder();
try {
    if (flagEncoding) {
        postPara = URLEncoder.encode(postPara);
    }

    url = new URL(serverUrl);
    conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "text/plain");
    conn.setRequestProperty("Content-Length", 
                                               Integer.toString(postPara.length()));
    conn.setDoInput(true);

    postReq = new PrintWriter(
                      new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    postReq.write(postPara);
    postReq.flush();

    postRes = new BufferedReader(
                     new InputStreamReader(conn.getInputStream(), "UTF-8"));
    while ((line = postRes.readLine()) != null){
        json.append(line);
    }
    conn.disconnect();
} catch (MalformedURLException ex) {
    throw new Exception(ex.getMessage());
} catch (IOException ex) {
    throw new Exception(ex.getMessage());
} catch (Exception ex) {
    throw new Exception(ex.getMessage());
}
return json.toString(); 
}   

출처 : http://www.jopenbusiness.com/tc/oss/entry/Android에서-Json-사용하여-통신하기-1?category=15

Be First to Comment

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다