2012-02-29 57 views
1

我是http編程的新手,我試圖對不使用API​​的網站進行身份驗證,但遇到了一些麻煩。我發現了其他幾個似乎與我的相似的問題,但沒有一個答案對我有用。如何使用Apache HttpClient 4.2.1或>對網站進行身份驗證?

我試過幾種不同的方法,但還沒有找到一個工程呢。其實,我曾經爲我工作過一次,但沒有檢查這些代碼(我知道 - 我在想什麼?)。我一直無法再回到那個工作版本。這裏是我到目前爲止已經試過幾件事情:

HttpClient client = new DefaultHttpClient(); //or any method to get a client instance, with a 'threadsafe' connection manager or otherwise 
    Credentials credentials = new UsernamePasswordCredentials(userName, passwd); 
    ((DefaultHttpClient) client).getCredentialsProvider() 
           .setCredentials(AuthScope.ANY, credentials); 

// website is defined as my target website & this constitutes the valid login URL 
    HttpPost post = new HttpPost(https + website + "/login"); 
    HttpEntity entity = new StringEntity("Username="+ userName +"&Password="+ passwd); 
    post.setEntity(entity); 

    HttpResponse response = client.execute(post); 
    EntityUtils.consume(entity); 
    entity = response.getEntity(); 
    EntityUtils.consume(entity); 

// the protected part of the site is over http after authentication succeeds 
    HttpGet get = new HttpGet(http + website +"/protected"); 
    response = client.execute(get); 
    entity = response.getEntity(); 
    String content = EntityUtils.toString(entity); 

此時的「實體」我從網站後面是「錯誤」:「未經授權的訪問」

你會注意到我有一個'Credentials'實例被傳遞給HttpClient,我也把用戶名&的密碼放在HttpPost實體中。我單獨嘗試了這些方法,並且都返回了「錯誤」:「未經授權的訪問」。結果。

我試過DefaultHttpClient,它使用單線程連接管理器,以及「ThreadSafeClientConnManager」,都沒有工作。

+0

發佈一個鏈接至您正在嘗試連接的網站,無需 – alfasin 2012-03-01 00:17:39

+0

@alfasin [www.centraldispatch.com](http://www.centraldispatch.com) 謝謝。 – SecondSun24 2012-03-01 01:08:53

回答

2

第一次嘗試登錄使用這個網址(複製網址到textpad什麼 - 然後編輯):

https://www.centraldispatch.com/login?uri=%2Fprotected%2F&Username=XXX&Password=YYY

與真實用戶只需更換XXX和YYY /傳 - 確保有用。

然後使用:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
nameValuePairs.add(new BasicNameValuePair("Username","Your username")); 
nameValuePairs.add(new BasicNameValuePair("Password","Your password")); 
post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
HttpResponse response = client.execute(post); 
BufferedReader rd = new BufferedReader(new InputStreamReader(
    response.getEntity().getContent())); 
    String line = ""; 
    while ((line = rd.readLine()) != null) { 
     System.out.println(line); 
    } 
+0

我沒有意識到我可以指定憑證。謝謝!我嘗試了你的方法,並沒有真正爲這個特定的網站工作。但是,它確實提醒我注意一個事實,即我整天都有我的憑證輸入錯誤。非常尷尬,至少可以說,但我的代碼現在正在工作。所以,你的確從根本上解決了我的問題,而且我仍然獲得了另一種用於工具腰帶的工具。非常感謝你。 – SecondSun24 2012-03-01 06:52:23

0

你有沒有設置用戶代理提起那一樣?

get.setHeader("Content-Type", "text/html"); 
get.setHeader("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50215;)"); 
get.setHeader("Accept-Charset", Chareset+";q=0.7,*;q=0.7");//"utf-8;q=0.7,*;q=0.7"); 

也許你應該首先獲得登錄頁面,以使用cookie。

如果所有這些都不起作用,那麼你應該使用一些工具,比如firebug + firefox來跟蹤網絡進程,然後一步一步地啓動它們。這應該起作用。

網站檢查一些領域,我認爲這絕對是原因。

相關問題