简体   繁体   中英

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

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....

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. We don't know what was my mistake. We are using 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. client.BaseAddress = new Uri("http:***.***.*.**");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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