2014년 12월 10일 수요일

HttpURLConnection

- URL 내용을 읽어오거나, URL 주소에 GET / POST로 데이터를 전달 할 때 사용함
- 웹 페이지나 서블릿에 데이터를 전달 수  있음
- URL --> openConnection() --> URLConnection  --> getInputStream --> InputStream (내용읽음)
- URL 의 OpenStream() : URL의 입력 스트림만 개설 (차이점)
- URLConnection : URL의 입력, 출력 스트림 개설

Construct 
protected URLConnection(URL) : 직접 생성 불가능 , OpenConnection으로 연결함
    
Method
addRequestProperty(String a, String b) : 키(a) 와 값(b)을 가지고 요청할 수 있는 
                               Properity 값을 미리 설정해 놓음. 특정 키값을 가지고 읽을 수 있도록 함
connect() : 연결 된 곳에 접속 할때 (connect() 호출해야 실제 통신 가능함)
getAllowUserInteraction() : 연결 된 곳에 사용자가 서버와 통신 할 수 있는 환경 확인(boolean)
                               in/output이 해당 서버 , 연결 포트로 가능한지 확인함
getContent() : content 값을 리턴 받음 (inputStream 값을 리턴 함)
getContent(Class[]) : 위 내용을 class[] 배열 값을 입력함
getContentEncoding() : 인코딩 타입을 String으로 리턴함
getContentLength() : content 길이 (-1 이면 정상적으로 값이 넘어오지 않았음)
getContentType() : content 가 http로 되어 있는지 타입 (ex: http-type )
getDate() : content의 날짜 (new Date(~~) 으로 변환해 줘야 함 / Long 리턴)
getDefaultAllowUserInteraction(): 기본적으로 User와 통신 가능한 상태인지 (boolean)
getDefaultUserCaches() : cache를 사용할 것 인지 (boolean)
getDoInput() : Server에서 온 데이터를 입력 받을 수 있는 상태인지 (본인 상태-default : true)
getDoOutput() : Server에서 온 데이터를 출력 할수 있는 상태인지
                          (Client 상태 -default : false)
getExpiration() : 유효 기간
getFileNameMap() : File Name Map
getHeaderField(int) : Head Field 값 받아옴 (http Head 값)
getHeaderFiled(String) :
getLastModified() : 마지막 수정 시간 

getInputStream() : InputStrema 값을 뽑아냄
getOutputStream() : OutputStream 값을 뽑아냄

setDoInput(boolean) : Server 통신에서 입력 가능한 상태로 만듬 
setDoOutput(boolean) : Server 통신에서 출력 가능한 상태로 만듬
 - Server와 통신을 하고자 할때는 반드시 위 두 method를 true로 해 놔야 함

----------------------------------------------------------------------------------------------------------------------------------

URL url = new URL("주소");
HttpURLConnection con = (HttpURLConnection)url.openConnection();

// 서버로부터 메세지를 받을 수 있도록 한다. 기본값은 true이다.
con.setDoInput(true); 

// 헤더값을 설정한다.
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// 전달 방식을 설정한다. POST or GET, 기본값은 GET 이다.
con.setRequestMethod(method);

// 서버로 데이터를 전송할 수 있도록 한다. GET방식이면 사용될 일이 없으나, true로 설정하면 자동으로 POST로 설정된다. 기본값은 false이다.
con.setDoOutput(true);

// POST방식이면 서버에 별도의 파라메터값을 넘겨주어야 한다.
String paramstr = buildParameters(params);
OutputStream out = con.getOutputStream();
out.write( paramstr.getBytes("UTF-8") );
out.flush();
out.close();

// con.getResponseCode();

// 결과값을 가져온다.
InputStream in = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
try
{
    in = con.getInputStream();
    while(true)
    {
        int readlen = in.read(buf);
        if( readlen < 1 )
            break;
        bos.write(buf, 0, readlen);
    }
    String output = new String(bos.toByteArray(), "UTF-8");
    System.out.println(output);
}catch (Exception e){
    e.printStackTrace();
}finally{
    if(bos != null) try{bos.close();}catch(IOException aa){}
    if(in != null) try{bos.close();}catch(IOException aa){}
}

호출후에는 응답을 꼭 받아야한다.
con.getResponseCode();
그렇지 않으면 연결자체를 하지 않는다.

in = con.getInputStream();
in.close();
이렇게 InputStream을 가져와도 호출이 가능하다.

즉, 요청후에는 getResponseCode()를 호출하거나 InputStream()을 얻어야 정상적으로 연결이 이루어진다.

아래는 POST로 파라메터값을 보낼때 유용한 메소드입니다.
rath님의 me2day라이브러리를 참조했습니다.

private String buildParameters( Map params )  throws IOException
{
    StringBuilder sb = new StringBuilder();
    for(Iterator i= params.keySet().iterator(); i.hasNext(); )
    {
        String key = (String)i.next();
        sb.append( key );
        sb.append( "=" );
        sb.append( URLEncoder.encode((String)params.get(key), "UTF-8") );
        if( i.hasNext() )
        sb.append( "&" );
    }
    return sb.toString();
}

댓글 없음:

댓글 쓰기