我正在构建一个 xamarin 库/插件,该插件应该使用 refit 调用 API,但是当我调用 API 时出现以下错误:
System.Net.Http.HttpRequestException: Connection refused ---> System.Net.Sockets.SocketException: Connection refused System.Net.Http.HttpRequestException: Connection refused ---> System.Net.Sockets.SocketException: Connection refused
at System.Net.Http.ConnectHelper.ConnectAsync (System.String host, System.Int32 port, System.Threading.CancellationToken cancellationToken) [0x00110] in <99e6bf9d99304315ba19eacc7497e256>:0
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.ConnectAsync (System.String host, System.Int32 port, System.Threading.CancellationToken cancellationToken) [0x001ac] in <99e6bf9d99304315ba19eacc7497e256>:0
at System.Threading.Tasks.ValueTask`1[TResult].get_Result () [0x0001b] in <6de48997d0c0445dbea8d4d83492d8c6>:0
at System.Net.Http.HttpConnectionPool.CreateConnectionAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x00134] in <99e6bf9d99304315ba19eacc7497e256>:0
at System.Threading.Tasks.ValueTask`1[TResult].get_Result () [0x0001b] in <6de48997d0c0445dbea8d4d83492d8c6>:0
我的 SDK 代码:接口
namespace Plugin.MySDK
{
public interface ISDK
{
[Post("/cart")]
Task<Events> postCart([Body] Events events);
}
}
MySDK.android.cs 我在其中进行 api 调用
namespace Plugin.MySDK
{
public class MySDK
{
static Activity currentActivity;
private static string _ms = "abcd";
private static string _appName;
private static string BASE_URL = "http://b80502ca.ngrok.io";
public TerraSDK()
{
}
public static void initialize(Activity activity,
string app)
{
currentActivity = activity;
_appName = app;
}
public static async void Cart()
{
try
{
var apiResponse = RestService.For<ISDK>(BASE_URL);
Events events = new Events();
events.ms = _ms;
events.app = _appName;
Events ev = await apiResponse.postCart(events);
Console.WriteLine("Response: " + ev);
}
catch (Exception ex)
{
Console.WriteLine("Cart:" + ex);
}
}
}
}
使用 SDK:
namespace TestSdk.Droid
{
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
Button cart;
private static string _appName = "TestSdk";
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.SetContentView(Resource.Layout.Main);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
cart = FindViewById<Button>(Resource.Id.cart);
MySDK.initialize(this,_appName);
cart.Click += this.Message;
}
public void Message(object sender, EventArgs e)
{
MySDK.Cart();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
但是当我尝试从应用程序以相同的方式调用 API 时,一切都按预期工作。如果我做错了什么,请帮助并纠正我,我是 xamarin 的新手