2013-03-22 110 views
1

我正在使用以下代碼發送REST請求,請求失敗(401錯誤),因爲它需要用戶名和密碼。如何將參數添加到寧靜的請求?

如何將它們添加到網址?即使當我在瀏覽器中複製url並在其末尾添加用戶名和密碼時,瀏覽器彈出登錄頁面,所以我想在代碼中我應該添加用戶名和密碼參數,但是如何?

URL url = new URL("www.example.com/user?ID=1234"); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/json"); 
       if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { 
      throw new RuntimeException("Failed : HTTP error code : " 
       + conn.getResponseCode()); 
     } 

我在代碼中添加了以下內容,但仍遇到401錯誤。

   conn.setRequestProperty("username", "myusername"); 
      conn.setRequestProperty("password", "mypassword"); 
+1

[看看這個](http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post) – SudoRahul 2013-03-22 04:29:05

回答

1

試試這個:

String params="username=myusername&password=mypassword"; 
conn.getOutputStream().write(params.getBytes()); 
conn.getOutputStream().flush(); 
conn.getOutputStream().close(); 

或者,也許你需要編碼PARAMS:

DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); 

String postContent = URLEncoder.encode("username", "UTF-8") + "=" + 
        URLEncoder.encode(myusername, "UTF-8") + "&" + 
        URLEncoder.encode("password", "UTF-8") + "=" + 
        URLEncoder.encode(mypassword, "UTF-8") ; 

dos.write(postContent.getBytes()); 
dos.flush(); 
dos.close(); 

關於Basic Authorization

String userPassword = username + ":" + password; 
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); 
URLConnection uc = url.openConnection(); 
uc.setRequestProperty("Authorization", "Basic " + encoding); 
uc.connect(); 
+0

謝謝,但它仍然遇到錯誤401,我雙還檢查了用戶名和密碼。 – 2013-03-22 04:41:27

+0

@DanielMorgan HTTP 401錯誤代碼表示請求未能提供正確的身份驗證,並且已被拒絕站點訪問。 – lichengwu 2013-03-22 04:49:50

+0

我知道,但服務器名稱和密碼是正確的 – 2013-03-22 04:53:59

相關問題