我正在使用以下代碼發送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");
[看看這個](http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post) – SudoRahul 2013-03-22 04:29:05