sitelink1 http://swlock.blogspot.kr/2015/03/httpurlconnection.html 
sitelink2  
sitelink3  

앞에서 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

번호 제목 글쓴이 날짜 조회 수
28 Android Studio for beginners, Part 3: Build and run the app file 황제낙엽 2018.02.02 81
27 Android Studio for beginners, Part 2: Explore and code the app(2) file 황제낙엽 2018.02.02 17
26 Android Studio for beginners, Part 2: Explore and code the app(1) file 황제낙엽 2018.02.02 36
25 Android Studio for beginners, Part 1: Installation and setup file 황제낙엽 2018.02.02 23
24 SDK와 NDK, 그리고 PDK 황제낙엽 2018.01.30 69
23 Error:Execution failed for task ':app:lintVitalRelease'. 황제낙엽 2018.01.29 783
22 Error:The number of method references in a .dex file cannot exceed 64K. 황제낙엽 2018.01.29 70
21 30일 기한 Google Play 개발자 약관 위반 알림 황제낙엽 2018.01.21 125
20 애니메이션 샘플 예제들 file 황제낙엽 2018.01.08 186
19 ConstraintLayout으로 숫자패드 레이아웃을 file 황제낙엽 2017.11.09 144
18 RecyclerView란? (RecyclerView와 ListView 차이) file 황제낙엽 2017.09.11 153
17 Android - Actionbar에 tab을 추가하고 스와이프 동작으로 화면 전환 구현( ViewPager와 FragmentPagerAdapter 사용) file 황제낙엽 2017.09.11 308
16 HTTP 프로토콜을 이용한 Json Post 보내고 받기 file 황제낙엽 2017.08.03 816
» HttpURLConnection 에서 세션 유지하기(쿠키 사용) 황제낙엽 2017.08.03 661
14 Android HttpURLConnection클래스로 POST 요청하기 황제낙엽 2017.08.01 65
13 Android’s HTTP Clients & Apache HTTP Client 어느것이 성능이 더 좋을까? 황제낙엽 2017.07.31 157
12 프로젝트의 AndroidManifest.xml 파일의 내용 file 황제낙엽 2017.07.25 52
11 구글의 안드로이드 개발자들이 만든 애플리케이션 모음 (Apps for Android ) file 황제낙엽 2017.07.25 56
10 크롬에서 디바이스(스마트폰) 연결 정보 확인 황제낙엽 2017.03.28 215
9 JNI 사용시 Android.mk와 Application.mk에 대해서 황제낙엽 2017.03.28 28