how to post string to URL in UWP

℡╲_俬逩灬. 提交于 2019-12-14 03:28:00

问题


i want to post a string to an URL so that i can upload a file. I did it in WPF project and i want to do it in UWP project. this is my method in WPF:

  OpenFileDialog ofd = new OpenFileDialog();

  string url = "http://localhost/visualStudioUpload/upload1.php ";

  WebClient Client = new WebClient();
            WebRequest request = WebRequest.Create(url);
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            byte[] byteArray = Client.UploadFile(url, "POST", ofd.FileName);

           request.ContentLength = byteArray.Length;

            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();

            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            //                  dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.

            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

回答1:


You can upload a file with the HttpClient (which replaces the WebClient in UWP)

Code:

private async Task<string> UploadImage(byte[] file, Uri url)
{
    using (var client = new HttpClient())
    {
        MultipartFormDataContent form = new MultipartFormDataContent();
        var content = new StreamContent(new MemoryStream(file));
        form.Add(content, "postname", "filename.jpg");
        var response = await client.PostAsync(url, form);
        return await response.Content.ReadAsStringAsync();
    }
}


来源:https://stackoverflow.com/questions/43679280/how-to-post-string-to-url-in-uwp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!