[英]Java HTTP Request with Token Authentication
我正在嘗試向正在運行的本地服務器發出GET請求。 我在返回正確的數據時遇到問題,看到“未經授權”的回復。 給定String'token'是正確的,誰能發現任何明顯的問題。
protected Object doInBackground(Void... params) {
try {
String url = "http://192.168.0.59:8000/events/";
URL object = new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization:", "Token " + token);
//Display what the GET request returns
StringBuilder sb = new StringBuilder();
int HttpResult = con.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
} else {
System.out.println(con.getResponseMessage());
}
} catch (Exception e) {
Log.d("Uh Oh","Check your network.");
return false;
}
return false;
} *
我能夠從命令行獲得curl請求:
curl -H "Authorization: Token token" http://0.0.0.0:8000/events/
事實證明,此問題是由包含con.setDoOutput(true);
引起的con.setDoOutput(true);
因為獲取請求不包含主體。
試試這個con.setRequestProperty(“ Authorization”,“ Bearer” +令牌);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.