发送Json作为正文和文件webrequest

时间:2018-01-23 11:50:03

标签: c# json httpwebrequest

如何发送正文和文件?

来自API指南:"Upload Requests are submitted with multiple parts: body (request) and file buffer (file)."

我知道如何只发送一个Json作为正文,但我现在需要将Json作为正文和文件发送。

我的代码类似于:

            const string WEBSERVICE_URL = "https://myurl.com";
            var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
            webRequest.Method = "POST";
            webRequest.ContentType = "multipart/form-data;boundary=12345678912345678912345678";
            webRequest.Headers.Add("Authorization:7786FFFGFDDDP");

      string json="{"\some json"\ :\"here\" }"
        using (var streamWriter = new StreamWriter(webRequest.GetRequestStream()))
        {

            streamWriter.Write(json);             
        }

        var httpResponse = (HttpWebResponse)webRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            Console.WriteLine(result.ToString());
        }

但如何将文件和正文一起发送?我的意思是我还要上传一些带有路径@c:\\myFile.txt

的文件

1 个答案:

答案 0 :(得分:0)

我需要在Xamarin应用程序中执行此操作。使用基于令牌的身份验证将图像发布到Web api。我在代码中进行了一些更改,以便在Web应用程序中使用。

public async void SendFile()
{
    using (System.IO.FileStream stream = System.IO.File.Open(@"c:\file.txt", System.IO.FileMode.Open))
    {
        var content = new System.Net.Http.MultipartFormDataContent();
        content.Add(new System.Net.Http.StreamContent(stream),
                "\"file\"",
                "Path to your file (ex: c:\temp\file.txt");

        await PostItemAsyncWithToken("url to post", content, "accessToken");
    }
}

public async System.Threading.Tasks.Task<bool> PostItemAsyncWithToken(string url, System.Net.Http.HttpContent content, string accessToken)
{
    try
    {
        using (var httpClient = new System.Net.Http.HttpClient())
        {
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
            System.Net.Http.HttpResponseMessage response = await httpClient.PostAsync(url, content).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
    catch (System.Exception ex)
    {
        throw new System.Exception("Error message", ex);
    }
}