安卓App网站登录遇问题:正确账号密码仍提示Login Failed
Hey there! Let's break down what's going wrong with your login code and get you back on track. First off, I notice a few key issues that are probably causing the "Login Failed!" toast even with correct credentials:
- Deprecated HttpClient: The
DefaultHttpClientyou're using was deprecated way back in Android 6.0 (API 23). Android now recommends modern alternatives likeHttpURLConnectionor OkHttp, which are more reliable and easier to debug. - Network on Main Thread: You're running the network request directly in the
doLoginmethod, which executes on the main UI thread. Android blocks network operations here to prevent app freezes (ANRs), so this is almost certainly throwing an exception that gets caught by your generic catch block. - Vague Error Handling: Your catch block only shows a generic toast without logging the actual exception. You have no way to know if it's a network error, invalid endpoint, or parameter mismatch.
- Possible Incorrect Endpoint: You're sending the POST request to
https://my.network.lviv.ua/—this looks like the website's homepage, not the dedicated login API endpoint. Most sites use paths like/loginor/api/authfor handling login requests.
Step-by-Step Fixes & Improvements
1. Switch to OkHttp (Recommended)
First, add OkHttp to your app's module-level build.gradle:
dependencies { implementation 'com.squareup.okhttp3:okhttp:4.12.0' }
2. Move Network Requests to a Background Thread
Use OkHttp's asynchronous calls to avoid blocking the main thread. Here's a rewritten version of your doLogin method:
public void doLogin(View v) { String username = ((EditText) findViewById(R.id.editTextUsername)).getText().toString(); String password = ((EditText) findViewById(R.id.editTextPassword)).getText().toString(); OkHttpClient client = new OkHttpClient(); // Package credentials into form-encoded data (matches how web forms send data) FormBody formBody = new FormBody.Builder() .add("username", username) .add("password", password) .build(); // Replace with the actual login endpoint of your website Request request = new Request.Builder() .url("https://my.network.lviv.ua/login") .post(formBody) .build(); // Execute request asynchronously client.newCall(request).enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { // Log the exact error to debug (check Logcat in Android Studio) e.printStackTrace(); // Show error toast on UI thread runOnUiThread(() -> Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_SHORT).show()); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { if (response.isSuccessful()) { String responseData = response.body().string(); // Validate if the response confirms successful login // (e.g., check for a "success" flag or user data in the response) runOnUiThread(() -> { // Navigate to the next Activity on success Intent intent = new Intent(MainActivity.this, YourNextActivity.class); intent.putExtra("username", username); // Pass data if needed startActivity(intent); }); } else { // Login failed (wrong credentials, server error, etc.) runOnUiThread(() -> Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_SHORT).show()); } } }); }
3. Fix Error Logging
In the onFailure method, e.printStackTrace() will print the exact error to Android Studio's Logcat. This will tell you if it's a network issue (no internet), invalid URL, or SSL certificate problem.
4. Verify the Login Endpoint & Parameters
- Double-check the website's actual login API endpoint. Use tools like Postman to test sending a POST request with correct credentials to confirm the endpoint works.
- Ensure parameter names (
username/password) match exactly what the website expects—some sites useemailinstead ofusername, orpassinstead ofpassword.
Understanding the Username/Password Flow
Let's clarify how the data moves between your app and the website:
- Your app collects username/password from the EditTexts.
- It packages these values into a form-encoded request body (mimicking how HTML forms send data).
- The POST request is sent to the website's login endpoint.
- The website's server validates the credentials against its database.
- The server sends back a response:
- Success: A 200 OK status plus any user data you might need.
- Failure: An error status (like 401 Unauthorized) or a failure message.
- Your app reads the response and acts accordingly—navigate to the next screen or show an error toast.
Additional Tips
- Add internet permission to your
AndroidManifest.xmlif you haven't already:<uses-permission android:name="android.permission.INTERNET" /> - For Android 9.0+, if your website uses HTTP (not HTTPS), you'll need a network security config to allow cleartext traffic. Since you're using HTTPS, this shouldn't be an issue.
内容的提问来源于stack exchange,提问作者vt-dev0
相关产品推荐
相关产品推荐

