Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c# - how to post string to URL in UWP

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...