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

2024-04-20

我正在尝试向我正在运行的本地服务器发出 GET 请求。我无法返回正确的数据,我看到“未经授权”的响应。鉴于字符串“令牌”是正确的,任何人都可以发现任何明显的问题吗?

    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.setRequestProperty("授权", "承载者" + token);

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用令牌身份验证的 Java HTTP 请求 的相关文章

随机推荐