使用MultipartFormDataContent

时间:2015-07-29 12:32:43

标签: c# json post windows-phone content-type

我需要将一些数据发布到API,但我不确定在哪里放置标题。这是我的代码:

    private async Task<string> PostTest()
    {
        string boundary = "----CustomBoundary" + DateTime.Now.Ticks.ToString("x");
        string servResp = "";

        strURI = "www.something.."
        HttpClient httpClient = new HttpClient();

        httpClient.DefaultRequestHeaders.Remove("Content-Type");
        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary);

        using (var content = new MultipartFormDataContent(boundary))
        {
            content.Add(new StringContent("application/json"), "Expected-Response-Mime-Type");
            content.Add(new StringContent("en-US"), "language");
            content.Add(new StringContent("blue"), "color");
            content.Add(new StringContent("12/11/15"), "date");

            ImageForm.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
            content.Add(ImageForm, "myPic", MyFileName);

            HttpClientHandler handler = new HttpClientHandler();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, strExpenseURL);
            request.Headers.ExpectContinue = false;
            request.Content = content;

            httpClient = new HttpClient(handler);

            HttpResponseMessage response = await httpClient.SendAsync(request);

            servResp = await response.Content.ReadAsStringAsync();
        }

        return servResp;
    }

我希望我的请求内容类型为:&#34; multipart / form-data;边界=&#34; +边界

和我的回复内容类型:&#34; application / json&#34;

这些是我设置这两个的正确位置吗?

1 个答案:

答案 0 :(得分:1)

尝试:

HttpClient client = new HttpClient();
HttpMultipartFormDataContent multipart = new HttpMultipartFormDataContent();
multipart.Add(new HttpStringContent("Bob"), "name");
multipart.Add(new HttpStringContent("Hero"), "job", "foo.txt");
multipart.Add(new HttpBufferContent((new byte[] { 0x21, 0x22, 0x23, 0x24 }).AsBuffer()), "Thing3");
HttpResponseMessage response = await client.PostAsync(uri, multipart);

的Debug.WriteLine(response.Content);

了解更多here

相关问题