Android使用Retrofit2发送POST请求失败,报405 Method Not Allowed错误
Retrofit2 POST请求到Laravel返回405 Method Not Allowed 问题解决
问题详情
尝试从Android应用通过Retrofit2向Laravel后端发送POST请求,请求失败,返回错误:Response{protocol=http/1.1, code=405, message=Method Not Allowed, url=http://192.168.68.108/api/data/configuration}
Android端代码
ApiService接口
@POST("api/data/configuration") Call<Data> postConfigurationData(@Body Data datosNuevos);
请求调用代码
Call<Data> dataCall = service.postConfigurationData(datosNuevos); dataCall.enqueue(new Callback<Data>() { @Override public void onResponse(Call<Data> call, Response<Data> response) { if(response.isSuccessful()){ Toast.makeText(Course.this, "El post se hizo correctamente", Toast.LENGTH_SHORT).show(); }else{ try { Toast.makeText(Course.this, response.errorBody().string(), Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(Course.this, e.getMessage(), Toast.LENGTH_LONG).show(); } } } @Override public void onFailure(Call<Data> call, Throwable t) { Toast.makeText(Course.this, "网络请求失败", Toast.LENGTH_SHORT).show(); } });
解决步骤
1. 检查Laravel路由定义
打开routes/api.php,确认路由使用POST方法定义,且URI完全匹配:
// 正确的POST路由示例 Route::post('/data/configuration', [ConfigurationController::class, 'store']);
- 必须使用
Route::post(),不能用get()、put()等其他HTTP方法 - 注意Laravel API路由默认带
api/前缀,所以路由URI是/data/configuration,对应完整请求路径http://192.168.68.108/api/data/configuration
2. 验证控制器方法
确保控制器的处理方法能接收并响应POST请求:
use App\Models\Data; use Illuminate\Http\Request; class ConfigurationController extends Controller { public function store(Request $request) { // 验证请求字段(根据你的Data模型调整规则) $validatedData = $request->validate([ 'field_name' => 'required|string', 'another_field' => 'integer', // 添加其他字段验证规则 ]); // 处理数据,比如存入数据库 $data = Data::create($validatedData); // 返回JSON响应,结构需和Android端的Data实体类匹配 return response()->json($data, 201); } }
3. 核对Retrofit Base URL配置
确保Retrofit的Base URL配置正确,避免路径重复:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://192.168.68.108/") // 末尾保留斜杠 .addConverterFactory(GsonConverterFactory.create()) .build();
如果Base URL设置为http://192.168.68.108/api/,则接口注解应改为@POST("data/configuration"),防止路径重复导致错误。
4. 确认API路由中间件
Laravel的API路由默认排除了CSRF验证,检查app/Http/Kernel.php中的api中间件组:
protected $middlewareGroups = [ 'api' => [ 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ];
不要将API路由放在web中间件组下,否则需要处理CSRF令牌,这会导致POST请求被拦截。
5. 直接测试接口可用性
用curl或Postman直接发送POST请求测试后端接口,验证是否是Laravel端问题:
curl -X POST http://192.168.68.108/api/data/configuration \ -H "Content-Type: application/json" \ -d '{"field_name":"测试值","another_field":123}'
如果直接测试也返回405,说明问题完全在Laravel路由配置,和Android代码无关。
内容的提问来源于stack exchange,提问作者Luis Yiao
相关产品推荐
相关产品推荐

