apache Android模拟器中的Socket Exception错误

pjngdqdw  于 2023-03-24  发布在  Apache
关注(0)|答案(1)|浏览(142)

我是laravel和flutter的新手,所以我成功地配置了我的laravel后端。我使用postman测试了API并成功地发布到数据库,现在当我尝试使用androind模拟器发布数据时,我一直收到错误(SocketException. connection refused(OS error. connection refused,ernno=111)address=127.0.0.1,port keeps changing)

我的API客户端如下

import 'package:myapp/utils/app_constants.dart';
import 'package:get/get.dart';

class ApiClient extends GetConnect implements GetxService{
  late String token;
  final String appBaseUrl;

  late Map<String, String> _mainHeaders;

  ApiClient({required this.appBaseUrl}){
    baseUrl = appBaseUrl;
    timeout = const Duration(seconds: 30);
    token = AppConstants.TOKEN;
    _mainHeaders ={
      'Content-type':'application/json; charset=UTF-8',
      'Authorization': 'Bearer $token',
    };
  }

  void updateHeader(String token){
    _mainHeaders ={
      'Content-type':'application/json; charset=UTF-8',
      'Authorization': 'Bearer $token',
    };

  }
  Future<Response> getData(String uri,)async{
    try{
      Response response =await get(uri);
      return response;
    }catch(e){
      return Response(statusCode: 1, statusText: e.toString());
    }
  }
  Future<Response>postData(String uri, dynamic body) async {
    print(body.toString());
    try{
      Response response = await post(uri, body, headers: _mainHeaders);
      return response;
    }catch(e){
      print(e.toString());
      return Response (statusCode: 1, statusText: e.toString());
    }
  }
}

AppConstants.dart

class AppConstants{
  static const String APP_NAME ="RideSharing";
  static const int APP_VERSION = 1;

  static const String BASE_URL ="http://127.0.0.1:8000/";

  //auth end points
  static const String REGISTRATION_URI ="api/dv/auth/register";

  static const String TOKEN = "RideToken";

}

error screenshot

ojsjcaue

ojsjcaue1#

如果您在本地运行服务器并使用Android模拟器,那么您的服务器端点应该是10.0.2.2:8000而不是localhost:8000,因为AVD使用10.0.2.2作为主机环回接口(即localhost)的别名。
或者
代表localhost添加您当前的IP地址作为一个例子(我在linux环境)

sudo apt install net-tools
ifconfig

简单地替换了flutter应用程序http请求中的“localhost”。它将工作。

相关问题