Java HTTP Request with Token Authentication

2019-08-15 01:02发布

I am trying to make a GET request to a local server I have running. I am having trouble returning the correct data, I am seeing an 'Unauthorized' response. Can anyone spot any glaring issues with this given that the String 'token' is correct.

    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;

}*

I was able to get a curl request working from the command line:

curl -H "Authorization: Token token" http://0.0.0.0:8000/events/

2条回答
2楼-- · 2019-08-15 01:54

try this con.setRequestProperty("Authorization", "Bearer " + token);

查看更多
贼婆χ
3楼-- · 2019-08-15 01:55

It turns out this issue was caused by including the con.setDoOutput(true); as get requests do not include a body.

查看更多
登录 后发表回答