简体   繁体   English

如何在调用HttpClient PostAsync方法上传图像时解决HttpRequestException

[英]How to solve HttpRequestException while calling HttpClient PostAsync method to upload image

We are working on a chat app in xamarin ios native app and we want upload a image to server using HttpClient PostAsync() method, but its throw exception like 我们正在xamarin ios本机应用程序中的聊天应用程序上工作,我们想使用HttpClient PostAsync()方法将图像上传到服务器,但是它会抛出异常,例如

System.Net.Http.HttpRequestException: An error occurred while sending the request ---> System.Net.WebException: Error: ConnectFailure (No route to host) ---> System.Net.Sockets.SocketException: No route to host.... System.Net.Http.HttpRequestException:发送请求时发生错误---> System.Net.WebException:错误:ConnectFailure(到主机没有路由)-> System.Net.Sockets.SocketException:到主机没有路由....

Our code to upload after select a image is.. 我们选择图片后上传的代码是..

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);

    }
}

We are using same code in our xamarin android native app and its working good in android. 我们在xamarin android本机应用程序中使用了相同的代码,并且在android中运行良好。 We don't know what was my mistake. 我们不知道我的错误是什么。 We are using visual studio for mac. 我们正在使用Visual Studio for Mac。

Please help to solve this or tell me another method to upload... 请帮助解决此问题或告诉我另一种上传方法...

I think you might get better results with this: 我认为您可能会获得更好的结果:

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);

I have solved it by just putting the right uri in base address. 我已经通过在基址中放置正确的uri解决了它。 client.BaseAddress = new Uri("http:***.***.*.**");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM