Java 使用令牌身份验证的 HTTP 请求

Java HTTP Request with Token Authentication

我正在尝试向我拥有的本地服务器发出 GET 请求 运行。我在返回正确数据时遇到问题,我看到 'Unauthorized' 响应。鉴于字符串 '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.setRequestProperty("Authorization", "Bearer " + 代币);