下面是我試圖複製的curl命令:HttpUrlConnection身份驗證不起作用
下面是curl請求。
curl user:[email protected]:8080/foo/bar -d property_one=value_one -d property_two=value_two -d property_three=value_three
這裏是HttpURLConnection的
URL thisurl = new URL ("http://localhost:8080/foo");
String encoding = Base64Encoder.base64Encode("user:password");
HttpURLConnection connection = (HttpURLConnection) thisurl.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.addRequestProperty("property_one", "value_one");
connection.addRequestProperty("property_two", "value_two");
connection.addRequestProperty("property_three", "property_three");
connection.setRequestProperty ("Authorization", "Basic " + encoding);
InputStream content = (InputStream)connection.getInputStream();
在我得到一個401錯誤connection.getInputStream()行的代碼。我是否認證錯誤?
不知道這是否重要,但你的網址是不同的。 – Henry
你有沒有嘗試'connection.setDoOutput(true);'?獲取請求不允許輸出。 – Henry
1)cURL請求是一個'POST'請求。任何使用'-d'的請求都會隱式成爲'POST'。 2)數據應該作爲url編碼的表單參數發送到請求的主體中,而不是在請求屬性中。 3)'Content-Type'頭部隱式設置在'application/x-www-form-urlencoded'的cURL請求中。您應該在Java代碼中執行相同的操作。 –