Android OkHttp with Basic Authentication

后端 未结 12 1539
感动是毒
感动是毒 2020-12-07 12:58

I\'m using the OkHttp library for a new project and am impressed with its ease of use. I now have a need to use Basic Authentication. Unfortunately, there is a dearth of w

12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 14:00

    Okhttp3 with base 64 auth

    String endpoint = "https://www.example.com/m/auth/"
    String username = "user123";
    String password = "12345";
    String credentials = username + ":" + password;
    
    final String basic =
            "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
    Request request = new Request.Builder()
            .url(endpoint)
            .header("Authorization", basic)
            .build();
    
    
    OkHttpClient client = SomeUtilFactoryClass.buildOkhttpClient();
    client.newCall(request).enqueue(new Callback() {
    ...
    

提交回复
热议问题