2011-08-11 5 views
1

현재 잘 작동하는 로그인 페이지에 데이터를 게시하는 코드가 있습니다. 그러나 로그인 정보를 확인한 후에 페이지의 URL을 얻는 방법에 대해서는 약간 분실되어 있습니다.게시 데이터 후 페이지의 리디렉션 URL 얻기

기본적으로 login.aspx라는 데이터를 게시 할 대상 URL이 있습니다. login.aspx는 다시 자신에게 게시하고 로그인을 확인한 다음 유효하면 일부 page.aspx? custId = 12345

으로갑니다.

게시를 수행 한 후 HTTPUrlConnection에 대한 getURL 메서드를 사용하면 원하는 page.aspx URL이 아닌 login.aspx URL이 반환됩니다. setFollowRedirects(), 한 번 false 및 한 번 true로 시도했습니다 다른 것들 중 위치 헤더 (아무도 없음) 가져 오는 시도하고 아무것도 작동하지. 거기에 더 Location 헤더 없으며, 인, followRedirects (이것은 기본적으로 사실) true의 경우

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

public class LoginByHttpPost 
{ 
    private static final String POST_CONTENT_TYPE = "application/x-www-form-urlencoded"; 

    private static final String LOGIN_USER_NAME = "oipsl"; 
    private static final String LOGIN_PASSWORD = "poker"; 

    private static final String TARGET_URL = "http://www.clubspeedtiming.com/prkapolei/login.aspx"; 

    public static void main (String args[]) 
    { 
     System.out.println("Verifying user in Casa De Chad Database"); 
     LoginByHttpPost httpUrlBasicAuthentication = new LoginByHttpPost(); 
     httpUrlBasicAuthentication.httpPostLogin(); 
    } 

    /** 
    * The single public method of this class that 
    * 1. Prepares a login message 
    * 2. Makes the HTTP POST to the target URL 
    * 3. Reads and returns the response 
    * 
    * @throws IOException 
    * Any problems while doing the above. 
    * 
    */ 
    public void httpPostLogin() 
    { 
     try 
     { 
      // Prepare the content to be written 
      // throws UnsupportedEncodingException 
      String urlEncodedContent = preparePostContent(LOGIN_USER_NAME); 

      HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent); 
      urlConnection.setFollowRedirects(true); 
      System.out.println(urlConnection.getResponseCode()); 
      System.out.println(urlConnection.getHeaderFields()); 

      String response = readResponse(urlConnection); 

      System.out.println("Successfully made the HTPP POST."); 
      System.out.println("Received response is: " + response); 
     } 
     catch(IOException ioException) 
     { 
      System.out.println("Problems encountered."); 
     } 
    } 

    /** 
    * Using the given username and password, and using the static string variables, prepare 
    * the login message. Note that the username and password will encoded to the 
    * UTF-8 standard. 
    * 
    * @param loginUserName 
    * The user name for login 
    * 
    * @param loginPassword 
    * The password for login 
    * 
    * @return 
    * The complete login message that can be HTTP Posted 
    * 
    * @throws UnsupportedEncodingException 
    * Any problems during URL encoding 
    */ 
    private String preparePostContent(String loginUserName) throws UnsupportedEncodingException 
    { 
     // Encode the user name and password to UTF-8 encoding standard 
     // throws UnsupportedEncodingException 
     String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8"); 
     //Hidden fields also used for verification 
     String viewState = URLEncoder.encode("/wEPDwULLTIxMTU1NzMyNDgPZBYCAgMPZBYCAgkPPCsADQBkGAEFAmd2D2dkNyI00Mr5sftsfyEsC6YBMNkj9mI=", "UTF-8"); 
     String eventvalidation = URLEncoder.encode("/wEWBAK2l8HDAQKQoJfyDwK6z/31BQLCi9reA4vQxgNI61f/aeA7+HYbm+y+7y3g", "UTF-8"); 

     String content = "tbxRacerName="+encodedLoginUserName+"&__VIEWSTATE="+viewState+"&__EVENTVALIDATION="+eventvalidation; 

     return content; 

    } 

    /** 
    * Makes a HTTP POST to the target URL by using an HttpURLConnection. 
    * 
    * @param targetUrl 
    * The URL to which the HTTP POST is made. 
    * 
    * @param content 
    * The contents which will be POSTed to the target URL. 
    * 
    * @return 
    * The open URLConnection which can be used to read any response. 
    * 
    * @throws IOException 
    */ 
    public HttpURLConnection doHttpPost(String targetUrl, String content) throws IOException 
    { 
     HttpURLConnection urlConnection = null; 
     DataOutputStream dataOutputStream = null; 
     try 
     { 
      // Open a connection to the target URL 
      // throws IOException 
      urlConnection = (HttpURLConnection)(new URL(targetUrl).openConnection()); 

      // Specifying that we intend to use this connection for input 
      urlConnection.setDoInput(true); 

      // Specifying that we intend to use this connection for output 
      urlConnection.setDoOutput(true); 

      // Specifying the content type of our post 
      urlConnection.setRequestProperty("Content-Type", POST_CONTENT_TYPE); 

      // Specifying the method of HTTP request which is POST 
      // throws ProtocolException 
      urlConnection.setRequestMethod("POST"); 

      // Prepare an output stream for writing data to the HTTP connection 
      // throws IOException 
      dataOutputStream = new DataOutputStream(urlConnection.getOutputStream()); 

      // throws IOException 
      dataOutputStream.writeBytes(content); 
      dataOutputStream.flush(); 
      dataOutputStream.close(); 

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

      // Good practice: clean up the connections and streams 
      // to free up any resources if possible 
      if (dataOutputStream != null) 
      { 
       try 
       { 
        dataOutputStream.close(); 
       } 
       catch(Throwable ignore) 
       { 
        // Cannot do anything about problems while 
        // trying to clean up. Just ignore 
       } 
      } 
      if (urlConnection != null) 
      { 
       urlConnection.disconnect(); 
      } 

      // throw the exception so that the caller is aware that 
      // there was some problems 
      throw ioException; 
     } 
    } 

    /** 
    * Read response from the URL connection 
    * 
    * @param urlConnection 
    * The URLConncetion from which the response will be read 
    * 
    * @return 
    * The response read from the URLConnection 
    * 
    * @throws IOException 
    * When problems encountered during reading the response from the 
    * URLConnection. 
    */ 
    private String readResponse(HttpURLConnection urlConnection) throws IOException 
    { 

     BufferedReader bufferedReader = null; 
     try 
     { 
      // Prepare a reader to read the response from the URLConnection 
      // throws IOException 
      bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); 
      HttpURLConnection.setFollowRedirects(false); 
      urlConnection.connect(); 
      System.out.println(urlConnection.getHeaderFields()); 
      System.out.println("URL: "+urlConnection.getURL()); 
      String responeLine; 

      // Good Practice: Use StringBuilder in this case 
      StringBuilder response = new StringBuilder(); 

      // Read untill there is nothing left in the stream 
      // throws IOException 
      while ((responeLine = bufferedReader.readLine()) != null) 
      { 
       response.append(responeLine); 
      } 

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

      // throw the exception so that the caller is aware that 
      // there was some problems 
      throw ioException; 

     } 
     finally 
     { 
      // Good practice: clean up the connections and streams 
      // to free up any resources if possible 
      if (bufferedReader != null) 
      { 
       try 
       { 
        // throws IOException 
        bufferedReader.close(); 
       } 
       catch(Throwable ignore) 
       { 
        // Cannot do much with exceptions doing clean up 
        // Ignoring all exceptions 
       } 
      } 

     } 
    } 
} 
+0

DateInputStream을 제거하십시오. 필요하지 않습니다. – Bozho

+0

죄송합니다, 어디에서보고 있습니까? 난 단지 DataOutputStream을 참조하십시오 – oipsl

+0

예, 내 나쁜 - 출력, 입력하지 않습니다 – Bozho

답변

0

, 그것은 더 리디렉션이 없음을 의미. 브라우저 URL을 변경하지 않는 서버 측 리디렉션 (전달) 일 수 있습니다. 브라우저로 로그인하면 주소 표시 줄에 page.aspx?custId=12345이 표시됩니까?

+0

예, 브라우저를 통해 로그인하면 해당 page.aspx URL로 이동하게되고, 로그인 할 때 다시 게시하게됩니다. .aspx

html의 "action"태그를보고, page.aspx url을 가져 오는 무언가를합니다. – oipsl

+0

나에게 사이트가 표시되면 어떻게되는지 알 수 있습니다. – Bozho

+0

http://www.clubspeedtiming.com /prkapolei/login.aspx – oipsl