2012-01-04 1 views
0

Я пытаюсь использовать следующий код для входа на сайт и получения содержимого, но когда я запускаю код, вывод не читается, а код не дает никаких ошибка/исключение also.Is код работает и входа в систему сайта, но данные шифруются так это то, что его показ в консоли или есть какая-то проблема с кодомWeird output отображается в консоли, пытаясь войти в систему через java на сайте

import java.net.MalformedURLException; 
import org.apache.commons.httpclient.*; 
import org.apache.commons.httpclient.cookie.CookiePolicy; 
import org.apache.commons.httpclient.cookie.CookieSpec; 
import org.apache.commons.httpclient.methods.*; 
import org.apache.commons.httpclient.protocol.Protocol; 
import org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.commons.httpclient.HttpMethod; 
import org.apache.commons.httpclient.HttpClient; 
import org.apache.commons.httpclient.Cookie; 

import java.io.BufferedReader; 
import java.io.FileOutputStream; 
import java.io.InputStreamReader; 
import java.net.URL; 


    public class TestHttpClient { 
    public static String formPostUrl ="http://mims.com/" ; 
    public static String LOGON_SITE = "https://sso.mims.com/Account/SignIn"; 
    static final int LOGON_PORT = 80; 
    public static void main(String[] args) throws MalformedURLException 
    { 
    String nextHref=""; 
    HttpClient client = new HttpClient(); 

    HttpMethod authGetmethod = new GetMethod("https://sso.mims.com/Account/SignIn"); 
    authGetmethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1"); 
    authGetmethod.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    authGetmethod.setRequestHeader("Accept-Language","en-us,en;q=0.5"); 
    authGetmethod.setRequestHeader("Accept-Encoding","gzip,deflate"); 
    authGetmethod.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"); 
    authGetmethod.setRequestHeader("Keep-Alive","300"); 
    authGetmethod.setRequestHeader("Connection","keep-alive"); 

    //authGetmethod.setRequestHeader("Referer","https://login.findmespot.com/faces/welcome.jsp"); 

try 
{ 
    //send first request to capture cookie information 
    int status = client.executeMethod(authGetmethod); 


    BufferedReader br = new BufferedReader(new InputStreamReader(authGetmethod.getResponseBodyAsStream())); 

    String str =""; 
    String resultJsessionid=""; 
     while((str=br.readLine())!=null) 
      { 
      if(str.indexOf("ASP.NET_SessionId=")!=-1) 
      { 
       //capture Session ID 
       resultJsessionid=getJsessionid(str); 
       break; 
      } 
      } 

     //release connection for final login request 
    authGetmethod.releaseConnection(); 

     client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); 

    Cookie[] cookies = (Cookie[]) client.getState().getCookies(); 
    for (int i = 0; i < cookies.length; i++) { 
    Cookie cookie = cookies[i]; 
    System.err.println(
     "Cookie: " + cookie.getName() + 
     ", Value: " + cookie.getValue() + 
     ", IsPersistent?: " + cookie.isPersistent() + 
     ", Expiry Date: " + cookie.getExpiryDate() + 
     ", Comment: " + cookie.getComment()); 


    //PostMethod authpost = new PostMethod("https://login.findmespot.com/faces/welcome.jsp?jessionid="+resultJsessionid); 
    PostMethod authpost = new PostMethod("http://mims.com/"); 
    // Set Headers 
    authpost.setRequestHeader("http.Agent", "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1"); 
    authpost.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    authpost.setRequestHeader("Accept-Language","en-us,en;q=0.5"); 
    authpost.setRequestHeader("Accept-Encoding","gzip,deflate"); 
    authpost.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"); 
    authpost.setRequestHeader("Keep-Alive","300"); 
    authpost.setRequestHeader("Connection","keep-alive"); 
    authpost.setRequestHeader("Referer","https://sso.mims.com/Account/SignIn"); 



    // Prepare login parameters 
    NameValuePair inputtext1  = new NameValuePair("Email Address","myemailaddress"); 
    NameValuePair inputtext5 = new NameValuePair("Password", "password for login"); 

    authpost.setRequestBody(
     new NameValuePair[] {inputtext1,inputtext5}); 
    client.executeMethod(authpost); 
    System.out.println("Login form post: " + authpost.getStatusLine().toString()); 
    String readLine; 

     br = new BufferedReader(new InputStreamReader(authpost.getResponseBodyAsStream())); 
     while(((readLine = br.readLine()) != null)) { 
      System.out.println(readLine); 
      nextHref=getNexthref(readLine); 
     } 

     authpost.releaseConnection(); 


    Cookie[] cookies1 = (Cookie[]) client.getState().getCookies(); 
     for (int i1 = 0; i < cookies1.length; i++) { 
    Cookie cookie1 = cookies1[i1]; 
    System.err.println(
     "Cookie: " + cookie1.getName() + 
     ", Value: " + cookie1.getValue() + 
     ", IsPersistent?: " + cookie1.isPersistent() + 
     ", Expiry Date: " + cookie1.getExpiryDate() + 
     ", Comment: " + cookie1.getComment()); 



    HttpMethod authGetmethodNext = new GetMethod("https://sso.mims.com/Account/SignIn"+nextHref); 
    authGetmethodNext.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9"); 
    authGetmethodNext.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    authGetmethodNext.setRequestHeader("Accept-Language","en-us,en;q=0.5"); 
    authGetmethodNext.setRequestHeader("Accept-Encoding","gzip,deflate"); 
    authGetmethodNext.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"); 
    authGetmethodNext.setRequestHeader("Keep-Alive","300"); 
    authGetmethodNext.setRequestHeader("Connection","keep-alive"); 
    authGetmethodNext.setRequestHeader("Referer","https://login.findmespot.com/faces/welcome.jsp"); 


    client.executeMethod(authGetmethodNext); 
    System.out.println("Login form post: " + authGetmethodNext.getStatusLine().toString()); 

    PostMethod authpost1 = new PostMethod("http://mims.com/"); 
    // Set Headers 
    authpost1.setRequestHeader("http.Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.9) Gecko/2009040821 Firefox/3.0.9"); 
    authpost1.setRequestHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); 
    authpost1.setRequestHeader("Accept-Language","en-us,en;q=0.5"); 
    authpost1.setRequestHeader("Accept-Encoding","gzip,deflate"); 
    authpost1.setRequestHeader("Accept-Charset","ISO-8859-1,utf-8;q=0.7,*;q=0.7"); 
    authpost1.setRequestHeader("Keep-Alive","300"); 
    authpost1.setRequestHeader("Connection","keep-alive"); 
    authpost1.setRequestHeader("Referer","Referer: https://login.findmespot.com/faces /trackerunit.jsp"); 


      client.executeMethod(authpost1); 

     br = new BufferedReader(new InputStreamReader(authpost1.getResponseBodyAsStream())); 
     while(((readLine = br.readLine()) != null)) 
     { 
      System.out.println(readLine); 
      } 

    } 
    } 
} 
catch(Exception ex) 
{ 
    System.out.println(ex.getMessage()); 
} 


    } 
    public static String getJsessionid(String responseText) /// retu 
    { 

    String jsession=""; 
    int start_index= responseText.indexOf("ASP.NET_SessionId="); 
    if(start_index!=-1) 
    { 
     jsession= responseText.substring(start_index+11); 
    } 
    int last_index=jsession.indexOf("\""); 
    if(last_index!=-1) 
    jsession=jsession.substring(0,last_index); 
    return jsession; 
    } 

    public static String getNexthref(String inputhref) 
    { 
    String result_href=""; 
    int start_index=inputhref.indexOf("href='"); 
if(start_index!=-1) 
    { 
    result_href=inputhref.substring(start_index+6); 
} 
    int last_index=result_href.indexOf("'"); 
if(last_index!=-1) 
    result_href=result_href.substring(0,last_index); 

return result_href;}} 

Выход:

Cookie: ASP.NET_SessionId, Value: s3fiwpzoyblxnyk4qx0o22n5, IsPersistent?: false, Expiry Date: null, Comment: null 
Jan 04, 2012 1:22:43 PM org.apache.commons.httpclient.HttpMethodBase processResponseHeaders 
WARNING: Cookie rejected: "BALANCEID=mycluster2.node3". Illegal path attribute "/resources". Path of origin: "/" 
Login form post: HTTP/1.1 200 OK 
‹ 
$(w‚Ù¥WéÝ™á^ðá6ñQ 
ÿðѰ,´¨fë2‡LLÈþQNù¤]È¡¡4?ú…ËI³:”F~È¿¦xìëvLȹ÷´¦Ü|¬ÜH¾|3%†ä°ì.$i€F3'_œ‚ñ#AOþí`üCA•þ?ìq›Cö©ùÌÓÑÐÌATk|‚ɧ 
ûx,òþŒ!ïá‹xÖ~„ ‚TõJdAÿáî/<x]¥à!Á¦ö@ž¾°µè|‚‡Æ€DKû3úEâʳ§Q¶¦?Wô)éu’$ŽkI³¥”.[O Ö¬zÍ¿9ÊwÞ•ôƒþhÚšþñ?Ú•gzžQüHc¢^…\:â˼n)‡Qšé^?‚*©!“Ï’³ÎÑߎœHVÒxh˜>iúƒ !Xì#Ž”?£@—‰@?T-~DÄ¡ì£\·.÷U(L$í·$Jan 04, 2012 1:22:53 PM org.apache.commons.httpclient.SimpleHttpConnectionManager getConnectionWithTimeout 
WARNING: SimpleHttpConnectionManager being used incorrectly. Be sure that HttpMethod.releaseConnection() is always called and that only one thread and/or method is using this connection manager at a time. 
Jan 04, 2012 1:22:56 PM org.apache.commons.httpclient.HttpMethodBase processResponseHeaders 
WARNING: Cookie rejected: "BALANCEID=mycluster2.node3". Illegal path attribute "/resources". Path of origin: "/" 
‹ 

Зашифрованный текст намного больше, чем я показал, и это повторяется снова и снова в co nsole

+0

Можете ли вы предоставить простой и воспроизводимый пример кода, вызывающего эту проблему? Я сомневаюсь, что люди чувствуют, что читают все, чтобы найти проблему, если вы не хотите, чтобы ее рубили. –

+0

На самом деле я получил код отсюда http://stackoverflow.com/questions/790004/issue-with-trying-to-login-to-a-https-secure-using-apache-commons-httpclient-cla и ths site имеет captcha, так что можно обойти его – saum22

+0

Не могли бы вы удалить 'Accept-Encoding'? –

ответ

1

Я считаю, что зашифрованный контент является содержимым файла cookie. Кроме того, вы говорите, что вы не получаете никаких ошибок, то как вы объясните предупреждения при условии на выходе:

WARNING: Cookie rejected: "BALANCEID=mycluster2.node3". Illegal path attribute "/resources" 

Убедитесь, что вы используете куки правильно

+0

Но это предупреждение, вы хотите сказать, что мой куки не идет на сайт – saum22

+2

@ saum22 yes. Я говорю, что сайт отказывается от вашего файла cookie. Таким образом, блокировка вашего соединения –

 Смежные вопросы

  • Нет связанных вопросов^_^