2011-08-08 9 views
1

내 학교 무들 웹 페이지에 로그인하고 소스 코드를 다운로드하는 데 어려움이 있습니다. 지금까지 로그인하지 않은 로그인 페이지 인 크게 두 주 동안이 문제에 갇혀되었습니다 주시면 감사하겠습니다. 아래 코드는 본인이 아니지만 웹에서 찾은 여러 가지 예제의 수정 된 버전입니다.java로 로그인하고 쿠키를 저장하는 웹 페이지를 다운로드하여

import java.net.*; 
import java.io.*; 
import java.util.*; 

public class LoginByHttpPost 
{ 
    private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded";  
    private static final String LOGIN_USER_NAME = "myusername"; 
    private static final String LOGIN_PASSWORD = "mypassword"; 
    private static final String LOGIN_DOMAIN = "students.ltu.edu.au"; 

    private static final String TARGET_URL = "https://www.latrobe.edu.au/lms/login/"; 
    private String page =""; 

    public static void main (String args[]) 
    { 
     LoginByHttpPost httpUrlBasicAuthentication = new LoginByHttpPost(); 
     httpUrlBasicAuthentication.httpPostLogin(); 
    } 

    public void httpPostLogin() 
    { 
     try 
     { 
      String urlEncodedContent = preparePostContent(LOGIN_USER_NAME, LOGIN_PASSWORD, LOGIN_DOMAIN); 

      HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent); 

      page = readResponse(urlConnection); 

      System.out.println("Successfully made the HTPP POST."); 
      System.out.println("Recevied response is: '/n" + page + "'"); 

     } 
     catch(IOException ioException) 
     { 
      System.out.println("Problems encounterd."); 
     } 
    } 


    private String preparePostContent(String loginUserName, String loginPassword, String loginDomain) throws UnsupportedEncodingException 
    { 
     String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8"); 
     String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8"); 
     String encodedLoginDomain = URLEncoder.encode(loginDomain, "UTF-8"); 

     String content = URLEncoder.encode("username=", "UTF-8") + encodedLoginUserName 
      + URLEncoder.encode("&password=", "UTF-8") + encodedLoginPassword 
      + URLEncoder.encode("&domain=", "UTF-8") + encodedLoginDomain 
      + URLEncoder.encode("&Login=", "UTF-8") + URLEncoder.encode("Login", "UTF-8"); 

     return content; 

    } 


    public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException 
    { 
     DataOutputStream dataOutputStream = null; 
     HttpURLConnection conn = null; 
     String cookieFirst = null; 
     String cookieValue = null; 
     String totalCookie = ""; 
     try 
     { 
      CookieManager manager = new CookieManager(); 
      manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); 
      CookieHandler.setDefault(manager); 


      URL url = new URL(targetUrl); 
      conn = (HttpURLConnection)url.openConnection(); 

      conn.getContent(); 

      CookieStore cookiejar = manager.getCookieStore(); 
      List<HttpCookie> cookiesList = cookiejar.getCookies(); 
      for(HttpCookie cookiel: cookiesList) 
      { 
       totalCookie += cookiel+"; "; 
      } 
      totalCookie = totalCookie.substring(0, totalCookie.length()-1); 
      System.out.println("Total Cookie: " + totalCookie); 

     } 
     catch(Exception e) 
     { 
      System.out.println("Something went wrong"); 
     } 

     HttpURLConnection urlConnection = null; 

     try{ 
      URL url = new URL(targetUrl); 
      urlConnection = (HttpURLConnection)url.openConnection(); 
      urlConnection.setDoInput(true); 

      urlConnection.setDoOutput(true); 

      urlConnection.setUseCaches(true); 

      urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE); 

      urlConnection.setRequestProperty("Content-Length", Integer.toString(content.length())); 

      urlConnection.setInstanceFollowRedirects(true); 

      urlConnection.setRequestMethod("POST"); 

      urlConnection.setRequestProperty("Cookie", totalCookie); 

      urlConnection.connect(); 


      dataOutputStream = new DataOutputStream(urlConnection.getOutputStream()); 

      dataOutputStream.writeBytes(content); 
      dataOutputStream.flush(); 
      dataOutputStream.close(); 

     } 
     catch(IOException ioException) 
     { 
      System.out.println("I/O problems while trying to do a HTTP post."); 
      ioException.printStackTrace(); 

      if (dataOutputStream != null) 
      { 
       try 
       { 
        dataOutputStream.close(); 
       } 
       catch(Throwable ignore) 
       { 
       } 
      } 
      if (urlConnection != null) 
      { 
       urlConnection.disconnect(); 
      } 

      throw ioException; 
     } 

      return urlConnection; 

    } 


    private String readResponse(HttpURLConnection urlConnection) throws IOException 
    { 

     BufferedReader bufferedReader = null; 
     try 
     { 
      bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
      String responeLine; 

      StringBuilder response = new StringBuilder(); 

      while ((responeLine = bufferedReader.readLine()) != null) 
      { 
       response.append(responeLine + "\n"); 
      } 

      return response.toString(); 
     } 
     catch(IOException ioException) 
     { 
      System.out.println("Problems while reading the response"); 
      ioException.printStackTrace(); 
      throw ioException; 

     } 
     finally 
     { 
      if (bufferedReader != null) 
      { 
       try 
       { 
        bufferedReader.close(); 
       } 
       catch(Throwable ignore) 
       { 
       } 
      } 

     } 
    } 
} 

답변

1

훨씬 쉽기 때문에이 웹 페이지에 액세스하여 로그인하려면 웹 브라우저를 사용하고 일련의 텔넷 명령을 사용하지 않는 것이 좋습니다. 그런 다음 프로그래머는 쿠키와 URL 연결을 사용하여 하위 수준의 작업 순서가 아닌 프로그래밍 방식의 웹 브라우저를 사용하십시오. 또한 훨씬 쉬울 것입니다.

HtmlUnit은 프로그래밍 방식의 웹 브라우저입니다. Getting started page의 끝 부분에는 웹 페이지를로드하고 양식을 제출하는 예제가 나와 있습니다. HtmlUnit은 제출, 쿠키 처리, 인코딩 등을 처리합니다.

+0

빠른 답장을 보내 주셔서 감사합니다. 문자열로 페이지를 반환하는 방법은 무엇입니까? gwt 응용 프로그램에서 호출하여 인터페이스를 만들 수 있도록이 코드를 사용하고 있습니다. 이미 모든 메소드를 작성하여 문자열 페이지에 로그인해야합니다. –

+0

HtmlPage.getWebResponse(). getContentAsString()을 사용하면). javadoc에 대한 http://htmlunit.sourceforge.net/apidocs/index.html –

+0

정말 고맙습니다. 얼마나 실망 스럽습니까? D –

관련 문제