3

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/
7
  • You need to authenticate yourself. Commented Oct 25, 2017 at 0:50
  • see stackoverflow.com/questions/12732422/… Commented Oct 25, 2017 at 0:53
  • 1
    Drop the : in "Authorization:". Commented Oct 25, 2017 at 1:15
  • As @xiaofeng.li correctly pointed out, you have unnecessary : in header name, should be like this : con.setRequestProperty("Authorization", "Token " + token); Commented Oct 25, 2017 at 6:46
  • @rkosegi Thanks for the advice, when I include the colon I get a "Unauthorized" response, and without it I get an "Internal Server Error" response. Commented Oct 25, 2017 at 16:02

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.