Java.Net.SocketException错误:仅当发送大于50kbs的文件时,才会在System.Net.Http httpClient中发生套接字关闭

Java.Net.SocketException错误:仅当发送大于50kbs的文件时,才会在System.Net.Http httpClient中发生套接字关闭,http,xamarin,Http,Xamarin,我正在xamarin中制作一个程序,它使用http请求从net.core 2.0中制作的API获取数据,但一些请求(实际上大部分)最终导致以下错误: System.AggregateException: One or more errors occurred. ---> Java.Net.SocketException: Socket closed at Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod (Java.

我正在xamarin中制作一个程序,它使用http请求从net.core 2.0中制作的API获取数据,但一些请求(实际上大部分)最终导致以下错误:

  System.AggregateException: One or more errors occurred. ---> Java.Net.SocketException: Socket closed
  at Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <286213b9e14c442ba8d8d94cc9dbec8e>:0 
  at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualInt32Method (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <286213b9e14c442ba8d8d94cc9dbec8e>:0 
  at Java.Net.HttpURLConnection.get_ResponseCode () [0x0000a] in <b781ed64f1d743e7881ac038e0fbdf85>:0 
  at Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass45_0.<DoProcessRequest>b__1 () [0x00000] in <b781ed64f1d743e7881ac038e0fbdf85>:0 
  at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in <d4a23bbd2f544c30a48c44dd622ce09f>:0 
  at System.Threading.Tasks.Task.Execute () [0x00000] in <d4a23bbd2f544c30a48c44dd622ce09f>:0 
--- End of stack trace from previous location where exception was thrown ---
  at Xamarin.Android.Net.AndroidClientHandler+<DoProcessRequest>d__45.MoveNext () [0x0036c] in <b781ed64f1d743e7881ac038e0fbdf85>:0 
--- End of stack trace from previous location where exception was thrown ---
  at Xamarin.Android.Net.AndroidClientHandler+<SendAsync>d__40.MoveNext () [0x00230] in <b781ed64f1d743e7881ac038e0fbdf85>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0 
   --- End of inner exception stack trace ---
  at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <d4a23bbd2f544c30a48c44dd622ce09f>:0 
  at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in <d4a23bbd2f544c30a48c44dd622ce09f>:0 
  at System.Threading.Tasks.Task`1[TResult].get_Result () [0x0000f] in <d4a23bbd2f544c30a48c44dd622ce09f>:0 
  at FonoApp.Services.DataService.SendImageAsync (System.String token, FonoApp.Model.Imagem imagem) [0x00059] in C:\Projetos Sorri\FonoApp\AppTeste\AppTeste\Services\DataService.cs:154 
   --- End of inner exception stack trace ---}
System.AggregateException:发生一个或多个错误。-->Java.Net.SocketException:套接字已关闭
在Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod(Java.Interop.JniObjectReference实例,Java.Interop.JniMethodInfo方法,Java.Interop.JniArgumentValue*args)[0x00069]中:0
在Java.Interop.jnipermembers+JniInstanceMethods.invokevirtualint32方法(System.String encodedMember,Java.Interop.IJavaPeerable self,Java.Interop.JniArgumentValue*参数)[0x0002a]中:0
在:0中的Java.Net.HttpURLConnection.get_ResponseCode()[0x0000a]处
在Xamarin.Android.Net.AndroidClientHandler+c_uu中显示class45_0.b_u1()[0x00000]in:0
在0中的System.Threading.Tasks.Task`1[TResult].InnerInvoke()[0x0000f]处
在0中的System.Threading.Tasks.Task.Execute()[0x00000]处
---来自引发异常的上一个位置的堆栈结束跟踪---
在Xamarin.Android.Net.AndroidClientHandler+d_u45.MoveNext()[0x0036c]中:0
---来自引发异常的上一个位置的堆栈结束跟踪---
在Xamarin.Android.Net.AndroidClientHandler+d_u40.MoveNext()[0x00230]中:0
---来自引发异常的上一个位置的堆栈结束跟踪---
在System.Net.Http.HttpClient+d__49.MoveNext()[0x000ca]中:0
---内部异常堆栈跟踪的结束---
0中的System.Threading.Tasks.Task.ThrowifeException(System.Boolean IncludeTaskCanceledException)[0x00011]处
位于:0中的System.Threading.Tasks.Task`1[TResult].GetResultCore(System.Boolean waitCompletionNotification)[0x0002b]
在System.Threading.Tasks.Task`1[TResult].get_Result()[0x0000f]中:0
在C:\Projetos-Sorri\FonoApp\AppTeste\AppTeste\AppTeste\Services\DataService.SendImageAsync(System.String令牌,FonoApp.Model.Imagem-Imagem)[0x00059]中
---内部异常堆栈跟踪结束---}
此代码段中出现此错误:

public async Task<String> SendImage(string token, Imagem imagem)
        {
            string baseAddress = @"http://192.168.0.4:5000/" + VersaoApi + @"/Imagem/";
            var json = JsonConvert.SerializeObject(imagem);
            var contentString = new StringContent(json, Encoding.UTF8, "application/json");
            client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", token);

            try
            {
                HttpResponseMessage tokenResponse = client.PostAsync(baseAddress, contentString).Result;//Erro ocorre nesta linha
                var jsonContent = tokenResponse.Content.ReadAsStringAsync().Result;
                return jsonContent;
            }
            catch (Exception e)
            {
                return e.InnerException.Message.ToString();
            }
        }
公共异步任务SendImage(字符串标记,Imagem-Imagem)
{
字符串基地址=@“http://192.168.0.4:5000/“+VersaoApi+@”/Imagem/”;
var json=JsonConvert.SerializeObject(imagem);
var contentString=newstringcontent(json,Encoding.UTF8,“application/json”);
client.DefaultRequestHeaders.Authorization=
新的AuthenticationHeaderValue(“承载者”,令牌);
尝试
{
HttpResponseMessageTokenResponse=client.PostAsync(baseAddress,contentString).Result;//Erro-ocorre-nesta-linha
var jsonContent=tokenResponse.Content.ReadAsStringAsync().Result;
返回jsonContent;
}
捕获(例外e)
{
返回e.InnerException.Message.ToString();
}
}
根据我的研究,并从这个错误中发现,这意味着服务器或客户端正在关闭连接,但我甚至不知道是谁突然关闭了连接,更不用说防止这个/异常错误了,我不知道这是否重要,但我正在安卓4.2-API 17平板电脑上测试该应用程序。由于我仍在学习如何用C#编程,因此提前感谢您对我的指导。 我以前忘了说的一件事是Postman API请求工作没有问题


我注意到了一个有趣的问题:只有在尝试通过http请求发送大于100 kb的图像时,才会出现错误。如何增加服务器上的发送和接收重量限制?

首先,您需要使用wait而不是Result(),以使此方法异步:

 var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
是的,当internet连接丢失时会发生此异常。您可以通过以下方式提高应用程序的可用性:

  • 在try catch块中显示警告消息
  • 使用Xamarin.Essentials.Connectivity插件检查internet连接
  • 为HttpClient对象设置超时,并捕获TimeoutException以显示正确的消息

  • 非常感谢你的帮助。我做了您告诉我的更改,当使用xamarin.Essentials.Connectvy测试网络时,我发现错误不会因为internet崩溃而发生,因为xamarin.Essentials.Connectvy的Connectivity.NetworkAccess始终显示我有网络。当我检查我的平板电脑时,我也注意到它有一个强大而稳定的网络连接。我注意到一件有趣的事情,我只在尝试通过http请求发送大于100KB的图像时才会出错,如何增加服务器上的发送和接收重量限制?您需要设置client.MaxResponseContentBufferSize=int.MaxValue,以便从服务器获取更大的文件。要将大文件发送到服务器,例如,我有一个10kb的映像,始终可以通过http post发送,但另一个120kbs总是在任务被取消时出错,sendi以及发送大文件?