java url 授权_Java:如何使用UrlConnection发布请求与授权?
我想生成POST請求到一個需要驗證的服務器。我試圖使用以下方法:
private synchronized String CreateNewProductPOST (String urlString, String encodedString, String title, String content, Double price, String tags) {
String data = "product[title]=" + URLEncoder.encode(title) +
"&product[content]=" + URLEncoder.encode(content) +
"&product[price]=" + URLEncoder.encode(price.toString()) +
"&tags=" + tags;
try {
URL url = new URL(urlString);
URLConnection conn;
conn = url.openConnection();
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
return rd.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return e.getMessage();
}
catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
}
但服務器不接收授權數據。應該添加授權數據的行如下:
conn.setRequestProperty ("Authorization", "Basic " + encodedString);
和線
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
也拋出一個IOException異常。
無論如何,我將非常感謝,如果任何人可以建議任何修正上述邏輯,以便啟用使用POST與UrlConnection的授權。
但顯然它不工作,因為它是應該的,雖然如果相同的邏輯用于GET請求一切正常。
總結
以上是生活随笔為你收集整理的java url 授权_Java:如何使用UrlConnection发布请求与授权?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: win10内存占用率过高怎么解决
- 下一篇: ASP.NET 2.0中怎么为GridV