You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android的AsyncTask或RequestHandler.java中添加Basic Auth认证?

Adding Basic Authentication to Android AsyncTask

Hey there! Let's get that Basic Auth working in your login AsyncTask. Basic Authentication works by encoding your username and password into a Base64 string and attaching it to the Authorization HTTP header of your request. Here are two straightforward ways to implement this based on your code:

Option 1: Modify the RequestHandler to Support Auth

Since you're using a RequestHandler class, adding an overloaded method that accepts authentication credentials is clean and reusable. Update your RequestHandler with this method:

public String sendGetRequest(String url, String username, String password) {
    StringBuilder response = new StringBuilder();
    try {
        URL urlObj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();

        // Encode credentials for Basic Auth
        String authString = username + ":" + password;
        String encodedAuth = Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);
        conn.setRequestProperty("Authorization", "Basic " + encodedAuth);

        conn.setRequestMethod("GET");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response.toString();
}

Then update your AsyncTask's doInBackground method to use this new method, and fix the Toast issue (you can't show Toasts from a background thread!):

@Override
protected String doInBackground(Void... params) {
    RequestHandler rh = new RequestHandler();
    // Pass username and password to the authenticated GET request
    return rh.sendGetRequest(App.URL_AUTHENTICATION, username, password);
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    loading.dismiss();
    // Move Toast here, since onPostExecute runs on the main thread
    Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
}

Option 2: Add Auth Directly in AsyncTask (Without Modifying RequestHandler)

If you don't want to alter the RequestHandler, you could handle the authentication inside doInBackground by creating the HTTP connection yourself (though reusing the RequestHandler is better practice). Here's how that would look:

@Override
protected String doInBackground(Void... params) {
    StringBuilder response = new StringBuilder();
    try {
        URL url = new URL(App.URL_AUTHENTICATION);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        // Add Basic Auth header
        String authString = username + ":" + password;
        String encodedAuth = Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);
        conn.setRequestProperty("Authorization", "Basic " + encodedAuth);

        conn.setRequestMethod("GET");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response.toString();
}

Important Notes:

  • Make sure you're using android.util.Base64 (not java.util.Base64) for compatibility across Android versions.
  • Never hardcode credentials! Always pass them dynamically like you're doing with username and password.
  • Background threads (like doInBackground) can't interact with the UI—so always move Toast, dialog updates, etc., to onPostExecute.

内容的提问来源于stack exchange,提问作者Nurdin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:39:58