对于具有Authorization = bearer token类型的GET请求的401未授权错误

时间:2018-01-10 04:10:53

标签: android web-services http httpurlconnection http-status-code-401

我正在使用"授权"制作HttpGet请求作为标题附加持票人令牌。我一直在收到401未经授权的错误。

我尝试过改造,但它没有工作,所以我又回到了基本的HTTP客户端。然后经过大量研究发现DefaultHttp存在一些错误。所以我改为HTTPUrlConnection。即使在完成所有这些操作后,我仍然会收到未经授权的401错误。我在这里可能做错了什么?由于此错误仍然存​​在,我决定坚持使用HTTPUrlConnection或DefaultHTTP并远离库。

这是我的HttpUrlConnection代码

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection)
                            obj.openConnection();
        con.setRequestMethod("GET");

        String authString = "Bearer" + accessToken;
        con.setRequestProperty("Authorization", authString);

        int responseCode = con.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) { // success
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    con.getInputStream()));
            String inputLine;
            response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

        } else {
            System.out.println("GET request not worked");
        }

这是我的DefaultHttp请求

        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGetRequest = new HttpGet(url);
        httpGetRequest.addHeader("Authorization","Bearer"+accessToken);
        try {
            HttpResponse response = client.execute(httpGetRequest);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new 
                InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
            }

3 个答案:

答案 0 :(得分:1)

Bearer cus之后添加一个空格,因为它与您的标记Bearer连接,并且标记为一个字符串

答案 1 :(得分:0)

请使用快速Android网络库,它非常易于使用,您可以在不到5分钟的时间内实现您的逻辑。所以请至少试一试。以下是图书馆的链接:

https://github.com/amitshekhariitbhu/Fast-Android-Networking

答案 2 :(得分:0)

问题解决了。我尝试使用retrofit和defaultHttpClient,但由于一些cookie问题,我都没有为我工作。但是使用OKHttpClient它是直接的,我能够点击服务器并获得响应。

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(mURL)
            .addHeader("Authorization", String.format("Bearer %s", bearerToken))
            .build();

        Response response = client.newCall(request).execute();
        return response.body().string();