반응형

HttpURLConnection 클래스는 URL 객체가 가리키는 자원의 HTTP 상태와 헤더 등의 정보를 제공합니다.

다음은 HttpURLConnection을 사용해 URL에 대한 정보를 얻어오는 예제입니다.
결과는 LogCat이 친절히 보여주는군요 ^^
해당 URL의 자원 내용을 가져오려면 getInputStream() 을 호출하면 됩니다.

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

//...중략

try {
        URL url = new URL("http://kkoseul.tistory.com/entry/2011080101");
        
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        Log.i("Net", "length = " + http.getContentLength());
        Log.i("Net", "respCode = " + http.getResponseCode());
        Log.i("Net", "contentType = " + http.getContentType());
        Log.i("Net", "content = " + http.getContent());

 


 
        InputStream isText = http.getInputStream();
         byte[] bText = new byte[2048];
         int readSize = isText.read(bText);
         Log.i("Net", "readSize = " + readSize);
         Log.i("Net", "bText = " + new String(bText));
         isText.close();
         http.disconnect();
 
     }catch(Exception e){
         Log.e("Net", "네트워크 에러가..났습니다...", e);
     }

//...생략


처음에 length 값이 '-1'이라 좀 의아해 했는데 찾아보니 getContentLength()는 명확하지 않으면 -1을 반환하는군요^^ 
반응형

+ Recent posts