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

如何在Java方法参数中传递方法?Android Studio接口调用方案咨询

Hey there! Let's tackle your problem step by step. Since you're working on replicating a website's login flow in Android Studio and want to pass logic into your SimpleGetRequest method, here are a few solid approaches you can use:


1. Use a Callback Interface (Classic Java Approach)

This is the standard way to pass "method-like logic" in Java—define a custom interface that outlines the behavior you want to trigger after the network request finishes.

First, create a callback interface to handle login success/failure:

public interface LoginResponseCallback {
    void onSuccess(JSONObject response);
    void onFailure(String errorMessage);
}

Next, update your SimpleGetRequest method to accept this callback as a parameter, and trigger the appropriate method once the request completes:

public void SimpleGetRequest(String url, LoginResponseCallback callback) {
    // Use AsyncTask to run the network request off the main thread
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL requestUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();
                connection.setRequestMethod("GET");

                // Read the response
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder responseBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    responseBuilder.append(line);
                }
                reader.close();
                connection.disconnect();
                return responseBuilder.toString();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                try {
                    JSONObject jsonResponse = new JSONObject(result);
                    callback.onSuccess(jsonResponse); // Trigger success logic
                } catch (JSONException e) {
                    callback.onFailure("Failed to parse login response");
                }
            } else {
                callback.onFailure("Network request failed");
            }
        }
    }.execute();
}

Now call your method and pass in the logic you want to run:

// Build your login URL (note: passing passwords via GET is insecure—more on that later!)
String loginUrl = "www.website.com/checkLogin.php?usr=username&pwd=password";

SimpleGetRequest(loginUrl, new LoginResponseCallback() {
    @Override
    public void onSuccess(JSONObject response) {
        // Handle login success here (e.g., parse user data, navigate to home screen)
        try {
            boolean loginSuccess = response.getBoolean("success");
            if (loginSuccess) {
                // Do something like start a new Activity
            } else {
                String errorMsg = response.getString("error");
                // Show error to user
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(String errorMessage) {
        // Handle failures (e.g., show a Toast to the user)
        Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
    }
});

2. Lambda Expressions (Java 8+)

If your project uses Java 8 or higher, you can simplify the callback code with lambdas. First, mark your callback interface as a functional interface (only one abstract method):

@FunctionalInterface
public interface LoginHandler {
    void handleResult(JSONObject response, String error);
}

Update SimpleGetRequest to use this interface:

public void SimpleGetRequest(String url, LoginHandler handler) {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            // Same network logic as before
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                try {
                    JSONObject jsonResponse = new JSONObject(result);
                    handler.handleResult(jsonResponse, null);
                } catch (JSONException e) {
                    handler.handleResult(null, "JSON parse error");
                }
            } else {
                handler.handleResult(null, "Network error");
            }
        }
    }.execute();
}

Call it with a concise lambda:

SimpleGetRequest(loginUrl, (response, error) -> {
    if (response != null) {
        // Success logic here
    } else {
        Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT).show();
    }
});

3. Leverage OkHttp's Built-in Callbacks (Cleaner Network Handling)

If you're open to switching from HttpURLConnection to a more modern library, OkHttp simplifies network requests and callbacks out of the box.

First, add OkHttp to your app-level build.gradle:

implementation 'com.squareup.okhttp3:okhttp:4.11.0'

Rewrite SimpleGetRequest with OkHttp:

public void SimpleGetRequest(String url, okhttp3.Callback callback) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .build();

    client.newCall(request).enqueue(callback); // Runs request on a background thread
}

Call it with OkHttp's callback (remember to update UI on the main thread!):

SimpleGetRequest(loginUrl, new okhttp3.Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
        // Update UI on main thread
        runOnUiThread(() -> Toast.makeText(MainActivity.this, "Request failed", Toast.LENGTH_SHORT).show());
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            try {
                JSONObject jsonResponse = new JSONObject(responseBody);
                runOnUiThread(() -> {
                    // Handle success logic here
                });
            } catch (JSONException e) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "Invalid response", Toast.LENGTH_SHORT).show());
            }
        } else {
            runOnUiThread(() -> Toast.makeText(MainActivity.this, "Server error: " + response.code(), Toast.LENGTH_SHORT).show());
        }
    }
});

Important Notes to Keep in Mind
  • Never pass passwords via GET: Your current URL includes the password as a query parameter, which is extremely insecure (it gets logged in server logs, browser history, etc.). Switch to a POST request and send credentials in the request body instead.
  • Network requests belong on background threads: Always avoid running network code on the main thread (Android will throw a NetworkOnMainThreadException). AsyncTask, OkHttp's enqueue, or coroutines are all safe options.
  • UI updates need the main thread: Any code that modifies the UI (like showing a Toast or navigating screens) must run on the main thread—use runOnUiThread() or a Handler for this.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:21:13