我是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」,都沒有工作。
發佈一個鏈接至您正在嘗試連接的網站,無需 – alfasin 2012-03-01 00:17:39
@alfasin [www.centraldispatch.com](http://www.centraldispatch.com) 謝謝。 – SecondSun24 2012-03-01 01:08:53