앞에서 HttpURLConnection 이용하여 웹페이지의 내용을 읽어오는 방법에 대해서 알아 보았습니다. 문제는 로그인 페이지가 있거나 하면 세션이 유지가 안되는 현상이 있어서 일부 site에서 사용하기에는 문제가 있었습니다.
그래서 기존 작성 코드에 쿠키를 저장하는 코드를 추가하였습니다.
saveCookie() 함수와 저장된 쿠키의 값을 전달해주는 부분이 변경 내용입니다. conn.setRequestProperty( "Cookie", m_cookies )

변경된 전체 소스를 공유합니다.

 

package com.example.zdgtest2;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

import android.util.Log;

public class GetHttp {
 final static double VERSION = 1.20141016;
 static final int ERROR_CODE_HTTP_NOT_FOUND = -404;
 static final int ERROR_CODE_HTTP_UNAUTHORIZED = -401;
 static final int ERROR_CODE_HTTP_ELSE = -1;
 static final int ERROR_CODE_HTTP_EXCEPTION = -1000;
 static final int ERROR_CODE_NOERROR = 0;
 byte[] htmlByte = null;
 int errorCode = 0;
 boolean bUseCache = true;
 boolean m_session = false;
 String m_cookies = "";
 public String getString() {
  try {
   return new String(htmlByte, "UTF-8");
  } catch (UnsupportedEncodingException e) {
   e.printStackTrace();
  }
  return null;
 }
 public byte[] getByte() {
  return htmlByte;  
 }
 public int getErrorCode() {
  return errorCode;
 }
 public boolean execute(String addr) {
  return execute(addr, 5, 10);
 }
 public void saveCookie( HttpURLConnection conn)
 {
  
     Map<String, List<String>> imap = conn.getHeaderFields( ) ;
     if( imap.containsKey( "Set-Cookie" ) )
     {
   List<String> lString = imap.get( "Set-Cookie" ) ;
   for( int i = 0 ; i < lString.size() ; i++ ) {
    m_cookies += lString.get( i ) ;
   }
   Log.e("zdg",m_cookies);
         m_session = true ;
     } else {
      m_session = false ;
     }
 }
 // 참고 소스:http://markan82.tistory.com/32
 public boolean execute(String addr, int connTimeOutSec, int readTimeOutSec) {
  boolean retval = true;
  errorCode = ERROR_CODE_NOERROR;
  try {
   URL url = new URL(addr);
   Log.e("zdg",addr);
   HttpURLConnection conn = (HttpURLConnection) url.openConnection();
   if( conn != null ) {
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
    if( m_session ) {
     conn.setRequestProperty( "Cookie", m_cookies );
    }
    conn.setConnectTimeout(1000*connTimeOutSec);
    conn.setReadTimeout(1000*readTimeOutSec);
    conn.setUseCaches(bUseCache);
    conn.setDoInput(true);

    int resCode = conn.getResponseCode();
    saveCookie(conn);

    if( resCode == HttpURLConnection.HTTP_OK ) {
     htmlByte = inputStreamToByte(conn.getInputStream());
     if(htmlByte == null || htmlByte.length == 0){
      errorCode = ERROR_CODE_HTTP_ELSE;
      retval = false;
     }
    } else if( resCode == HttpURLConnection.HTTP_NOT_FOUND ) {
     errorCode = ERROR_CODE_HTTP_NOT_FOUND;
     retval = false;
    } else if( resCode == HttpURLConnection.HTTP_UNAUTHORIZED ) {
     errorCode = ERROR_CODE_HTTP_UNAUTHORIZED;
     retval = false;
    } else {
     errorCode = ERROR_CODE_HTTP_ELSE;
     retval = false;
    }
    // DISCONNECT 
    conn.disconnect();
   } else {
    errorCode = ERROR_CODE_HTTP_ELSE;
    retval = false;
   }
  } catch(Exception e) {
   e.printStackTrace();
   errorCode = ERROR_CODE_HTTP_EXCEPTION;
   retval = false;
  }
  return retval;
 }
 private byte[] inputStreamToByte(InputStream in)
 {
  final int BUF_SIZE = 1024; 
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  byte[] buffer = new byte[BUF_SIZE];
  try {
   int length;
   while ((length = in.read(buffer)) != -1) out.write(buffer, 0, length);
  } catch (IOException e) {
   e.printStackTrace();
   return null;
  }
  return out.toByteArray();
 }
}



다음은 호출하는곳의 예제 코드입니다.

 

 private void webTest() {
  Thread nthread = new Thread(new Runnable() {
    public void run() {
     try {
      GetHttp html = new GetHttp();
    if(html.execute("http://xxx:8080/jsp/admin/user/userCtrl.jsp?id=xxx&pass=xxx",30,30)!=true)
    {
     printLog("error "+html.errorCode);
    }
    if ( html.getByte() != null && html.getByte().length > 0 ){
     Utils.fileWriteByte("/sdcard/Download/test1.html",html.getByte());
    }
    html.execute("http://xxx:8080/jsp/main.jsp",30,30);
    if ( html.getByte() != null && html.getByte().length > 0 ){
     Utils.fileWriteByte("/sdcard/Download/test2.html",html.getByte());
    }
     } catch (Throwable ex) {
      ex.printStackTrace();
     }
    }
   });
  nthread.start();
 }


안드로이드에서 호출할때는 main ui thread에서 호출하면 오류가 발생하기 때문에 thread를 사용하였습니다.
그리고 권한 <uses-permission android:name="android.permission.INTERNET" /> 을 추가해주어야 합니다.

추가내용
http://swlock.blogspot.kr/2016/07/http-session-html.html
위에서 쿠키 작업한 내용이 완벽하지 않습니다. 
https://en.wikipedia.org/wiki/HTTP_cookie 
https://tools.ietf.org/html/rfc2109
여기 보면 자세한 내용이 나오는데 안의 인자값에 따라 어떤 동작들을 해야합니다. 그러한 부분이 전혀 구현되어있지 않습니다.
따라서 완벽하게 하려면 httpclient libarary등의 라이브러리를 사용하시기 바랍니다.
http://swlock.blogspot.kr/2017/01/httpclient-use-in-android-httpclient.html

번호 제목 글쓴이 날짜 조회 수
128 PC를 위한 최고의 안드로이드 에뮬레이터 황제낙엽 2023.01.18 3132
127 [Jetpack Compose UI / 상추님] GDG Jetpack compose 코드랩 수료 후기 (feat. 굿즈) 황제낙엽 2022.12.24 2370
126 [Jetpack Compose UI / kyj1991719] compose - Compose 이해 황제낙엽 2022.12.24 4025
125 [Jetpack Compose UI / 꾸준] Compose 가 뭔데...? 황제낙엽 2022.12.24 4035
124 [Jetpack Compose UI / IIVIKI] Compose 학습과 분석 황제낙엽 2022.12.24 4050
123 [Jetpack Compose UI] 스터디 시작하기 황제낙엽 2022.12.24 4001
122 [개발하는 정대리] 취준생을 위한 안드로이드 앱만들기 - 바텀네비게이션 뷰, 네비게이션 AAC file 황제낙엽 2022.12.22 3882
121 [개발하는 정대리] 취준생을 위한 안드로이드 앱만들기 - 뷰바인딩 file 황제낙엽 2022.12.22 3850
120 [개발하는 정대리] 취준생을 위한 안드로이드 앱만들기 - 라이브데이터 뷰모델 file 황제낙엽 2022.12.21 3826
119 [대왕놀] ImageButton in Compose (IconButton) 황제낙엽 2022.12.20 4105
118 [대왕놀] compose instrumentation test tutorial 황제낙엽 2022.12.20 3985
117 [대왕놀] Switch in Compose 황제낙엽 2022.12.20 4106
116 [대왕놀] EditText in Compose (TextField) 황제낙엽 2022.12.20 4021
115 [대왕놀] margin in Compose 황제낙엽 2022.12.20 4105
114 [대왕놀] modifier in compose 황제낙엽 2022.12.20 4180
113 [대왕놀] Button in Compose file 황제낙엽 2022.12.20 4224
112 [대왕놀] TextView in Compose (Text) 황제낙엽 2022.12.20 4083
111 [대왕놀] ImageView in Compose (Image) 황제낙엽 2022.12.20 4017
110 [대왕놀] LinearLayout in Compose (Row, Column) 황제낙엽 2022.12.20 4113
109 [대왕놀] Introduction to Jetpack compose 황제낙엽 2022.12.20 3964