Search code examples
httpurlconnectionhttpconnection

Http Basic Authentification - Android - HttpURLConnection


I am trying to get http basic authentification, using HttpURLConnection, but setRequestProperty seems not functioning, because the response code from the connection is different from 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!");
            }

and the monitor shows :

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

Thank you for the help !


Solution

  • 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