2013-12-12 68 views
0

我正在尋找一個HTTP POST請求並使用結果auth_token,但while循環中的打印語句僅打印x-dnb-user=myusername&x-dnb-pwd=mypass,而不打印它從服務器接收到的響應。我無法弄清楚我出錯的地方。任何幫助,將不勝感激。此外,響應以字典形式給出,令牌存在於字典中的「授權」鍵中,在這種情況下,我將如何檢索令牌?java simple http auth不起作用

public void sampleAuth(){ 
     HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost("https://maxcvservices.dnb.com/rest/Authentication"); 
    try { 
     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
     nameValuePairs.add(new BasicNameValuePair("x-dnb-user","myemail")); 
     nameValuePairs.add(new BasicNameValuePair("x-dnb-pwd","mypass")); 
     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); 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

在此先感謝!

回答

0

我想你可能缺少的內容類型

post.setHeader("Content-type", "application/x-www-form-urlencoded"); 

此外,你開始rd.readLine響應之前,你應該檢查響應的狀態代碼。服務器可能會拒絕你,並且不會有線路可讀!

int code = response.getStatusLine().getStatusCode(); 
if (code == HttpStatus.SC_OK) { 
    // Now go fishing for the auth_token 
    // Usually these things are returned as headers 
} else { 
    System.out.println("You've been rejected, pal"); 
} 

我需要你期待的AUTH_TOKEN更多的細節,但我的猜測是,它由「AUTH_KEY」或類似的名稱的頭所以你可以看看它。

+0

嘿鮑勃感謝您的迴應。我確實收到了400碼,這就是爲什麼我認爲沒有什麼可讀的。問題是文檔說在HTTP標頭中傳遞用戶標識和密碼,但所有文檔都指示我將用戶標識和密碼作爲NameValuPairs傳遞,這正是我所遵循的。你認爲這可能是問題嗎?如果是這樣的話,我會如何傳遞一個post請求頭部的user_id和密碼? – anonuser0428

+0

我不知道,但如果文檔說一個標題給它一個標題。此外,如果他們想要實際的Http基本身份驗證,這是一個它自己擁有自己頭部和全部的規範:http://en.wikipedia.org/wiki/Basic_access_authentication。如果HttpClient對此沒有抽象,我會感到驚訝。 –