안드로이드/Android HttpUrlConnection JSON 으로 Request, Response 하기
HttpUrlConnection JSON 방식으로 Request, Response 하는 방법에 대해 알아 보겠습니다.
HttpURLConnection conn = null; OutputStream os = null; InputStream is = null; ByteArrayOutputStream baos = null; conn = (HttpURLConnection)url.openConnection(); conn.setConnectTimeout(CONN_TIMEOUT * 1000); conn.setReadTimeout(READ_TIMEOUT * 1000); conn.setRequestMethod(POST); conn.setRequestProperty("Cache-Control", "no-cache"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); JSONObject job = new JSONObject(); job.put("phoneNum", "01000000000"); job.put("name", "test name"); job.put("address", "test address"); os = conn.getOutputStream(); os.write(job.toString().getBytes()); os.flush(); String response; int responseCode = conn.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); byte[] byteBuffer = new byte[1024]; byte[] byteData = null; int nLength = 0; while((nLength = is.read(byteBuffer, 0, byteBuffer.length)) != -1) { baos.write(byteBuffer, 0, nLength); } byteData = baos.toByteArray(); response = new String(byteData); JSONObject responseJSON = new JSONObject(response); Boolean result = (Boolean) responseJSON.get("result"); String age = (String) responseJSON.get("age"); String job = (String) responseJSON.get("job"); Log.i(TAG, "DATA response = " + response); }
타입에대한 자세한 설명은,