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

Android Studio集成Laravel登录接口时出现Error Code 0求助

Android集成Laravel登录系统出现Error Code 0问题排查

我正在开发基于Laravel后端的Android登录系统,Postman测试后端能正常返回预期结果,但Android Studio用Java集成登录时持续出现Error Code 0错误,排查代码没找到问题,怀疑是HTTP请求处理或响应解析环节异常。相关代码如下:


Android端代码

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

public class Login extends AppCompatActivity {


    EditText etEmail, etPassword;
    Button bnLogin;
    String email, password;
    LocalStorage localStorage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        localStorage = new LocalStorage(Login.this);

        etEmail = findViewById(R.id.editTextTextEmailAddress2);
        etPassword = findViewById(R.id.editTxtPhone);

        bnLogin = findViewById(R.id.btn_login);
        bnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkLogin();
            }
        });
    }

    private  void checkLogin(){
        email = etEmail.getText().toString();
        password = etPassword.getText().toString();
        if(email.isEmpty() || password.isEmpty()){
            Toast.makeText(this, "Email and Password is required", Toast.LENGTH_SHORT).show();
        }
        else {
            sendLogin();
            Toast.makeText(this, "work and still ", Toast.LENGTH_SHORT).show();
        }
    }

    private void sendLogin(){
        JSONObject params = new JSONObject();
        try {
            params.put("email", email);
            params.put("password", password);
            String data = params.toString();
            String url = getString(R.string.api_server) + "login";
            // Log the data before sending the request
            Log.d("https send data", data);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Http http = new Http(Login.this, url);
                    http.setMethod("post");
                    http.setData(data);
                    http.send();
                    Log.d("https send data",   data);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Integer code = http.getStatusCode();
                            if(code == 200) {
                                try {
                                    JSONObject response = new JSONObject(http.getResponse());
                                    String token = response.getString("token");
                    
                                    localStorage.setToken(token);

                                    Intent intent = new Intent(Login.this, Dashborad.class);
                                    startActivity(intent);
                                    finish();
                                }catch (JSONException e){
                                    e.printStackTrace();
                                }
                            }
                            else if(code == 422) {
                                try {
                                    JSONObject response = new JSONObject(http.getResponse());
                                    String msg = response.getString("message");
                                    Toast.makeText(Login.this, msg, Toast.LENGTH_SHORT).show();
                                }catch (JSONException e){
                                    e.printStackTrace();
                                }
                            }
                            else if(code == 401) {
                                try {
                                    JSONObject response = new JSONObject(http.getResponse());
                                    String msg = response.getString("message");
                                    Toast.makeText(Login.this, msg, Toast.LENGTH_SHORT).show();
                                }catch (JSONException e){
                                    e.printStackTrace();
                                }
                            }
                            else {
                                Toast.makeText(Login.this, "Error "+code , Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
            }).start();


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Http工具类

package com.example.myapplication;

import android.content.Context;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Http {
    Context context;
    private String url, method="GET", data=null, response=null;
    private Integer statusCode = 0;
    private Boolean token = false;
    private LocalStorage localStorage;

    // Constructor with context and localStorage
    public Http(Context context, String url) {
        this.context = context;
        this.url = url;
        localStorage = new LocalStorage (context);
    }

    public void setMethod(String method) {
        this.method = method.toUpperCase();
    }

    public void setData(String data) {
        this.data = data;
    }

    public void setToken(Boolean token) {
        this.token = token;
    }

    public String getResponse() {
        return response;
    }

    public Integer getStatusCode() {
        return statusCode;
    }

    public void send(){
        try{
            URL surl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) surl.openConnection();
            connection.setRequestMethod(method);
            connection.setRequestProperty("Content-Type","application/json");
            connection.setRequestProperty("X-Requested-With", "WMLHttpRequest");
            if(token){
                connection.setRequestProperty("Authorization", "Bearer "+localStorage.getToken());
            }
            if(! method.equals("POST")){
                connection.setDoOutput(true);
            }
            if(data !=null){
                OutputStream os = connection.getOutputStream();
                os.write(data.getBytes());
                os.flush();
                os.close();
            }
            statusCode = connection.getResponseCode();

            InputStreamReader isr;
            if(statusCode >= 200 && statusCode <= 299){
                //if success response
                isr = new InputStreamReader(connection.getInputStream());
            }else {
                //if error response
                isr = new InputStreamReader(connection.getErrorStream());
            }

            BufferedReader br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null){
                sb.append(line);
            }
            br.close();
            response = sb.toString();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

LocalStorage工具类

package com.example.myapplication;

import android.content.Context;
import android.content.SharedPreferences;

public class LocalStorage {
    SharedPreferences sharedPreferences ;
    SharedPreferences.Editor editor;
    Context context;
    String token;

    public LocalStorage(Context context){
        this.context = context;
        sharedPreferences = context.getSharedPreferences("STORAGE_LOGIN_API", Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    public String getToken() {
        token = sharedPreferences.getString("TOKEN", "");
        return token;
    }

    public  void setToken(String token) {
        editor.putString("TOKEN", token);
        editor.commit();
        this.token = token;
    }
}

strings.xml配置

<resources>
    <string name="app_name">My Application</string>
    <string name="api_server">http://192.168.1.18:8000/api/</string>
</resources>

Laravel后端代码

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use App\Models\User;
use Illuminate\Support\Facades\Validator;

class AuthController extends Controller
{

      /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login', 'register']]);
    }

    public function index(Request $request){
        return $request->user();
    }

    public function login(Request $request) {
        $credentials = request(['email', 'password']);

        if (! $token = auth()->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $this->respondWithToken($token);
    }


       /**
     * Register a User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register() {
        $validator = Validator::make(request()->all(), [
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:8',
        ]);

        if($validator->fails()){
            return response()->json($validator->errors()->toJson(), 400);
        }

        $user = new User;
        $user->name = request()->name;
        $user->email = request()->email;
        $user->password = bcrypt(request()->password);
        $user->save();

        return response()->json($user, 201);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json(auth()->user());
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return response()->json(['message' => 'Successfully logged out']);
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => auth()->factory()->getTTL() * 60
        ]);
    }

}

路由配置

Route::match(['GET', 'POST'], '/login', [AuthController::class, 'login'])->name('login');

后端启动命令

php artisan serve --host=192.168.1.18

服务运行地址:http://192.168.1.18:8000


问题修复方案

1. 修正Http类的setDoOutput逻辑

Http类中这段代码逻辑完全错误,导致POST请求无法发送请求体:

if(! method.equals("POST")){
    connection.setDoOutput(true);
}

修复为:

if(method.equals("POST")){
    connection.setDoOutput(true);
}

原因:POST请求需要向服务器写入数据,必须开启DoOutput,原代码是POST请求时关闭该选项,导致请求无法正常发送,进而返回Error Code 0。

2. 修正JSON响应字段匹配

Laravel后端返回的token字段为access_token,但Android代码中错误获取token字段:

String token = response.getString("token");

修复为:

String token = response.getString("access_token");

原因:字段不匹配会抛出JSONException,导致登录成功后的逻辑无法执行。

3. 补充网络异常日志(可选)

在Http类的IOException捕获块中添加日志,方便定位网络连接问题:

catch (IOException e) {
    e.printStackTrace();
    Log.e("HttpError", "网络请求异常: " + e.getMessage());
    statusCode = -1; // 标记为网络异常,区分其他错误码
}

4. 确认网络权限

确保AndroidManifest.xml中已添加网络权限:

<uses-permission android:name="android.permission.INTERNET" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:52:03