我是 android 新手,这是我在 android 上的第一个项目。我在“身份验证”问题上苦苦挣扎了一天多。我尝试了几种选择,但都没有奏效。
基本上,我想调用 REST API 并获得响应。我确信 API 没有问题,因为我在另一个 iOS 应用程序中使用了相同的 API。
我通过了授权标头,但仍然没有显示身份验证消息。我在 stackoverflow 上发现了一些与此相关的问题,但其中一些不起作用,有些对我来说没有意义。
我得到状态码401。我知道这意味着要么没有通过身份验证,要么如果通过了,那么它们是错误的。在这里,我确信我通过的是正确的。
下面是我的代码:
try {
    url = new URL(baseUrl);
}
catch (MalformedURLException me) {
     Log.e(TAG, "URL could not be parsed. URL : " + baseUrl + ". Line : " + getLineNumber(), me);
     me.printStackTrace();
}
try {
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod(method); 
    urlConnection.setConnectTimeout(TIMEOUT * 1000);
    urlConnection.setChunkedStreamingMode(0);
    // Set HTTP headers                 
    String authString = "username:password";
    String base64Auth = Base64.encodeToString(authString.getBytes(), Base64.DEFAULT);
    urlConnection.setRequestProperty("Authorization", "Basic " + base64Auth);
    urlConnection.setRequestProperty("Accept", "application/json");
    urlConnection.setRequestProperty("Content-type", "application/json");
    if (method.equals("POST") || method.equals("PUT")) {
        // Set to true when posting data
        urlConnection.setDoOutput(true);
        // Write data to post to connection output stream
        OutputStream out = urlConnection.getOutputStream();
        out.write(postParameters.getBytes("UTF-8"));
    }
    try {
        // Get response
        in = new BufferedInputStream(urlConnection.getInputStream());
    }
    catch (IOException e) {
        Log.e(TAG, "Exception in getting connection input stream. in : " + in);
                    e.printStackTrace();
    }
    // Read the input stream that has response
    statusCode = urlConnection.getResponseCode();
    Log.d(TAG, "Status code : " + statusCode);
}
catch (ProtocolException pe) {
    pe.printStackTrace();
}
catch (IllegalStateException ie) {
    ie.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}   
finally {
    urlConnection.disconnect();
}
查看logcat 的屏幕截图:

任何帮助,将不胜感激。谢谢你。