Http请求返回401

时间:2015-12-16 12:32:13

标签: android httpresponse httpurlconnection

在我的项目中,我调用web服务来获取请求的json响应将需要用户名和密码进行身份验证。我已经在标题的标题中传递了用户名和密码。但请求返回401响应,这意味着凭据不正确。

这是我的代码。

String path = "http://example.com/mobile/GetMenuByCategoryId/3";
        try {
            String username = "usrename", password = "password";
            String joined = username + ":" + password;
            String authSring = "Basic "+Base64.encode(joined.getBytes(),Base64.DEFAULT);
            URL url = new URL(path);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Authorization", authSring);
            int responseCode = connection.getResponseCode();
            if (responseCode == 200){
                InputStream is= connection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder("");
                int line = 0;
                while((line = br.read())!=-1){
                    sb.append(line);
                }
                Log.e("RESPONSE", "response = \n "+ sb.toString() );
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

此代码有什么问题?

0 个答案:

没有答案