2011-08-16 4 views
0

httpリクエストでログイン値を投稿して保護されたhtmlページを表示しようとしています...このサイトはsportguru.co.ukであり、正しくパスワードを投稿できないようです。私はこのコード(私の実際のログインの詳細を)実行すると:HTTPフォームのログインプログラムで間違いはどこですか?

/** 
* $Id: LoginByHttpPost.java 101 2010-03-13 23:52:31Z oneyour $ 
* 
* This is an accompanying program for the article 
* http://www.1your.com/drupal/LoginToWebsiteByHTTPPOSTCodeListing 
* 
* Copyright (c) 2009 - 2010 www.1your.com. All rights reserved. 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions 
* are met: 
* 
* - Redistributions of source code must retain the above copyright 
*  notice, this list of conditions and the following disclaimer. 
* 
* - Redistributions in binary form must reproduce the above copyright 
*  notice, this list of conditions and the following disclaimer in the 
*  documentation and/or other materials provided with the distribution. 
* 
* - Neither the name of www.1your.com nor the names of its 
*  contributors may be used to endorse or promote products derived 
*  from this software without specific prior written permission. 
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
* 
*/ 

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_ACTION_NAME = "Log in"; 
    private static final String LOGIN_USER_NAME_PARAMETER_NAME = "email"; 
    private static final String LOGIN_PASSWORD_PARAMETER_NAME = "password"; 

    private static final String LOGIN_USER_NAME = "emailAddress"; 
    private static final String LOGIN_PASSWORD = "password"; 

    private static final String TARGET_URL = "http://www.sportguru.co.uk/login_form.asp"; 

    public static void main (String args[]) 
    { 
     System.out.println("About to run the 'LogInByHttpPost' downloaded from www.1Your.com"); 
     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, LOGIN_PASSWORD); 

      HttpURLConnection urlConnection = doHttpPost(TARGET_URL, urlEncodedContent); 

      String response = readResponse(urlConnection); 

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

      System.out.println("/n Hope you found the article and this sample program useful./nPlease leave your feed back at www.1your.com and support us."); 
     } 
     catch(IOException ioException) 
     { 
      System.out.println("Problems encounterd."); 
     } 
    } 

    /** 
    * 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, String loginPassword) throws UnsupportedEncodingException 
    { 
     // Encode the user name and password to UTF-8 encoding standard 
     // throws UnsupportedEncodingException 
     String encodedLoginUserName = URLEncoder.encode(loginUserName, "UTF-8"); 
     String encodedLoginPassword = URLEncoder.encode(loginPassword, "UTF-8"); 

     String content = "Log in=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"=" 
     + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword; 

     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())); 
      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('\n'+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 
       } 
      } 

     } 
    } 
} 

を私が受け取るHTMLページには、このフォームが含まれています

<form name="loginPage" method="post" action="login.asp" onSubmit="return submitForm()" style="margin:0px;padding:0px"> 
    <input type="hidden" name="pageReferer" value="" /> 
    <input type="hidden" name="logintype" value="page" /> 
    <input type="hidden" name="pagePoolCode" value="" /> 

<div style="border:2px solid #666666;width:486px"> 
    <div style="background-image:url(home/images/structure/header_login.gif);height:28px;"></div> 
    <div style="padding:7px;"> 
     <table cellspacing="2" cellspacing="0"> 
     <tr> 
      <td align="right" width="62">Email:</td> 
      <td><input type="text" name="pageEmail" value="emailAddress" size="32"></td> 
     </tr> 
     <tr> 
      <td align="right">Password:</td> 
      <td><input type="password" name="pagePassword" size="32"></td> 
     </tr> 
     <tr> 
      <td align="right"></td> 
      <td class="small"><a href="forgotten.asp"><strong>Forgotten</strong> your email address or password? Or has your<br /><strong>email changed</strong> since last you used the site? <strong>Click here</strong> &raquo;</a></td> 
     </tr> 
     <tr> 
      <td>&nbsp;</td> 
      <td style="padding-top:7px;"><input type="image" src="/home/images/buttons/login.gif" value="Log in"></td> 
     </tr> 

    </table> 
    </div> 
</div> 
</form> 

としては、メールアドレスが正しくフォームに掲載されて見ることができます。しかし、私はポストの後にHTMLページのソースを表示したい...私はクッキーや何かが必要ですか?

答えて

0

HTTPステータスコードを確認しましたか?リダイレクトがある可能性があります。

+0

んが、私は持っていないが、私はこれを行うことができますか? – FreddieH

+0

'urlConnection.getResponseCode()'を呼び出して、それが[302]かどうかを調べます(http://en.wikipedia.org/wiki/HTTP_302)。その後、リダイレクト先のURLのレスポンスの場所ヘッダーを確認できます。しかし、リダイレクトしている場合は、 'urlConnection.setInstanceFollowRedirects(boolean true)'を呼び出すことによってクライアントに自動的にリダイレクトを指示することができます。 – SingleShot

+0

レスポンスコード200と書かれていて、リダイレクトの自動化は自動化されましたが、それでも動作しません!返信されたhtmlで表示されますが、パスワードではない可能性があるので、Postは電子メールアドレスを使って作業しています。私はここに本当に困惑しています... – FreddieH

0
String content = "Log in=" + LOGIN_ACTION_NAME +" &" + LOGIN_USER_NAME_PARAMETER_NAME +"=" 
    + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword; 

実際にはLog inにスペースが必要ですか?

Log%20inまたはLog+inとなります。 (私はあなたの完全な形が表示されないように、私はここでしか推測できます。)


だから、我々はこれらのフォームフィールドに送信する必要があります:

  • pageReferer(空)
  • logintypeを( page
  • pagePoolCode(空)
  • pageEmail(メールアドレス?)
  • pagePassword(?パスワード)

<input type="image" src="/home/images/buttons/login.gif" value="Log in">あります - これは何の名前属性を持っていないので、それが送信することはできません。したがって、私の最初の推測では、コンテンツ文字列のこの部分を単に省略することになります。これが機能しない場合

String content = LOGIN_USER_NAME_PARAMETER_NAME + "=" 
    + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword; 

、文字列にも最初の3つのフィールドを追加していない:

String content = "pageReferer=&loginType=page&pagePoolCode=&" + 
    LOGIN_USER_NAME_PARAMETER_NAME + "=" 
    + encodedLoginUserName + "&" + LOGIN_PASSWORD_PARAMETER_NAME + "=" + encodedLoginPassword; 
+0

興味深い、私は戻って報告します...ありがとう! – FreddieH

+0

ここに全体の書式があります: – FreddieH

+0

@Freddie:質問に追加してください、コメントではありません。 –

関連する問題