Digest authentication in Android using HttpURLConnection

前端 未结 5 694
终归单人心
终归单人心 2020-12-03 16:05

as the question allready says, I am trying to do digest authentication in android.
Until now i have used the DefaultHttpClient and it\'s authentication meth

5条回答
  •  隐瞒了意图╮
    2020-12-03 16:44

    Did you try to set the header manually like:

    String basic = "Basic " + new String(Base64.encode("username:password".getBytes(),Base64.NO_WRAP ));
    connection.setRequestProperty ("Authorization", basic);
    

    Also be aware of some issues in Jellybeans and a bug when you try to perform a post request: HTTP Basic Authentication issue on Android Jelly Bean 4.1 using HttpURLConnection

    EDIT: For Digest authentication

    Have a look here https://code.google.com/p/android/issues/detail?id=9579

    Especially this might work:

    try {   
            HttpClient client = new HttpClient(
                    new MultiThreadedHttpConnectionManager());
    
            client.getParams().setAuthenticationPreemptive(true);
            Credentials credentials = new UsernamePasswordCredentials("username", "password");
            client.getState().setCredentials(AuthScope.ANY, credentials);
            List authPrefs = new ArrayList(2);
            authPrefs.add(AuthPolicy.DIGEST);
            authPrefs.add(AuthPolicy.BASIC);
            client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY,
                    authPrefs);
            GetMethod getMethod = new GetMethod("your_url");
            getMethod.setRequestHeader("Accept", "application/xml");
            client.executeMethod(getMethod);
            int status = getMethod.getStatusCode();
            getMethod.setDoAuthentication(true);
            System.out.println("status: " + status);
            if (status == HttpStatus.SC_OK) {
                String responseBody = getMethod.getResponseBodyAsString();
                String resp = responseBody.replaceAll("\n", " ");
                System.out.println("RESPONSE \n" + resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    

提交回复
热议问题