Http 基本身份验证 - Android - HttpURLConnection

Http Basic Authentification - Android - HttpURLConnection

我正在尝试使用 HttpURLConnection 获取 http 基本身份验证,但 setRequestProperty 似乎无法正常工作,因为来自连接的响应代码与 200 不同。

urlConnection = (HttpURLConnection) url.openConnection();

            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true); // automatically use POST method

            /*Header Set Up, based on HTTP Basic Authentification Method*/
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            String basic = "Basic " + Base64.encodeToString(("******:******").getBytes(), Base64.NO_WRAP);

            Log.d("TAG", basic);

            urlConnection.setRequestProperty("Authorization", basic);

            Log.d("TAG", urlConnection.toString());

            Log.d("TAG", "connect..");
            /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            int statusCode = urlConnection.getResponseCode();

            /* 200 represents HTTP OK */
            if (statusCode ==  200) {

                result = 1; // Successful
                Log.e("TAG", "Connection Success");

            }else{
                result = 0; //"Failed to fetch data!";
                Log.e("TAG", "Failed to fetch data!");
            }

并且监视器显示:

D/TAG: Basic aW50ZXJudGVzdDp0b2JwYW4zOTY3
D/TAG: com.android.okhttp.internal.http.HttpURLConnectionImpl: My URL
D/TAG: connect..
E/TAG: Failed to fetch data!

感谢您的帮助!

public void onReceivedHttpAuthRequest(WebView view, final HttpAuthHandler handler, String host, String realm) {
                    handler.proceed(TEST_USER, TEST_PASS);
                    super.onReceivedHttpAuthRequest(view, handler, host, 
                    //handler.cancel();

            }



@Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);}

...

Android Reference