【问题标题】:How to solve HttpRequestException while calling HttpClient PostAsync method to upload image调用HttpClient PostAsync方法上传图片时如何解决HttpRequestException
【发布时间】:2018-07-11 05:07:40
【问题描述】:

我们正在开发 xamarin ios 本机应用程序中的聊天应用程序,我们希望使用 HttpClient PostAsync() 方法将图像上传到服务器,但它会抛出异常

System.Net.Http.HttpRequestException:发送请求时出错---> System.Net.WebException:错误:ConnectFailure(没有到主机的路由)---> System.Net.Sockets.SocketException:否到主机的路由....

选择图片后我们要上传的代码是..

public async void UploadToServer(string filePath, string filename, string fileExtension,long fileSize)
{
    using(var client = new HttpClient())
    using(var content= new MultipartFormDataContent())
    {
        client.BaseAddress = new Uri("http://*////");

        var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filePath));

        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = filePath
        };

        content.Add(fileContent);

        var result = await client.PostAsync("api/FileUpload?groupID =" + ChatDetaiils.groupID + "&memberID=" + UserLogin.userID + "&Message=File Test&chatType=File&FileName="+filename+"&fileSize="+fileSize+"&fileExtension="+fileExtension+"",content);

    }
}

我们在我们的 xamarin android 本机应用程序中使用相同的代码,并且它在 android 中运行良好。 我们不知道我的错误是什么。我们正在使用 Visual Studio for mac。

请帮忙解决这个问题或告诉我另一种上传方法...

【问题讨论】:

  • 手机好像联系不上服务器了。
  • http: 您是否在应用的 info.plist 中允许不受信任的连接?
  • 请告诉我在 info.plist 中添加的键和值
  • 你在info.plist中添加了App Transport Security Settings
  • 我添加了 NSAppTransportSecurityNSAllowsArbitraryLoads 但它不起作用

标签: c# ios xamarin xamarin.ios


【解决方案1】:

我认为你可能会得到更好的结果:

var values = new Dictionary<string, string>
{
    { "groupID", ChatDetaiils.groupID },
    { "memberID", UserLogin.userID },
    { "Message", File },
    // etc..etc
};

var content = new FormUrlEncodedContent(values);

var result = await client.PostAsync("api/FileUpload, content);

【讨论】:

  • 你好它通过传递正确的uri解决了..这是我的错误。 client.BaseAddress = new Uri("http:***.***.*.**");
【解决方案2】:

我已经通过将正确的 uri 放入基地址来解决它。 client.BaseAddress = new Uri("http:***.***.*.**");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 1970-01-01
    • 2013-10-02
    • 2015-02-10
    相关资源
    最近更新 更多