안드로이드/Android HttpUrlConnection getResponseCode() == HttpURLConnection.HTTP_OK 처리 방법
안드로이드 HttpURLConnection 을 사용하여 서버와 통신을 하게 될 때, conn.getResponseCode() 의 Result 코드 값으로 HttpURLConnection.HTTP_OK(200) 받게 되는 경우 재대로 통신을 위한 준비가 되었다고 볼 수 있는데요. 이렇게 재대로 연결된 후에는 서버에서 내려주는 Byte들을 처리해서 xml 형식의 String으로 변환하는 방법 입니다.
InputStream is = null;
ByteArrayOutputStream baos = null;
if(conn.getResponseCode() == 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) {
baos.write(byteBuffer, 0, nLength);
}
byteData = baos.toByteArray();
//String response = new String(byteData, "euc-kr");
String response = new String(byteData);
if(response==null || response.equals("")) {
throw new Exception("Response is NULL!");
}
}