Java HTTP Request with Token Authentication

不打扰是莪最后的温柔 提交于 2019-12-11 09:47:38

问题


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/

回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/46922151/java-http-request-with-token-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!