如何在C#中使用具有复杂内容类型的HttpClient?

时间:2018-09-19 16:44:26

标签: c# http content-type

我正在尝试使用httpclient库,但问题出在此代码上

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://server/ucwa/oauth/v1/applications/10751539691/batch")
        {
            Content = new StringContent("", Encoding.UTF8, "multipart/batching;boundary=77f2569d") // CONTENT-TYPE header
        };

它崩溃并说

System.FormatException: 'The format of value 'multipart/batching;boundary=77f2569d' is invalid.'

但是,这很正常:

static void Test() {

    PostAsync("https://server/ucwa/oauth/v1/applications/10751539691/batch", "Bearer", "cwt=AAEBHAEFAAAAAAAFFQAAACd5t5mMpiIgog-06W0EAACBEJH-LcfxNO5SsZ3Ya9NHaRuCAluYgyChwp4HzFpww_sZkaK5SBFBUY4Uk3oW6u6U0Oeh9jWOZoYI8fwX34ce1ggNEJH-LcfxNO5SsZ3Ya9NHaRs", data, "multipart/batching", "multipart/batching;boundary=77f2569d");
}


    static void PostAsync(string uri, string token_type, string access_token, string postData, string accept, string content_type)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

        byte[] data = Encoding.ASCII.GetBytes(postData);

        request.Method = "POST";
        request.Accept = accept;
        request.ContentType = content_type;
        request.Headers.Add("Authorization", token_type + " " + access_token);
        request.ContentLength = data.Length;

        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
    }

    static void FinishWebRequest(IAsyncResult result)
    {
        HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
        string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
        Console.WriteLine(responseString);
        Console.ReadLine();
    }

有人知道这个问题是什么吗?我如何获得它接受该内容类型以使用httpClient发出请求?

谢谢

5 个答案:

答案 0 :(得分:0)

这是使用MediaTypeHeaderValue.Parameters进行此操作的一种方法:

var body = new StringContent("");
var header = new MediaTypeHeaderValue("multipart/batching");
header.Parameters.Add(new NameValueHeaderValue("boundary", "77f2569d"));
body.Headers.ContentType = header;

这发出的请求看起来像这样:

POST http://www.somewhere.com/ HTTP/1.1
Content-Type: multipart/batching; boundary=77f2569d
Host: www.somewhere.com
Content-Length: 11
Expect: 100-continue
Connection: Keep-Alive

hello world

答案 1 :(得分:0)

这种方法对我有用。我举两个例子,一个是添加字符串内容,另一个是添加字节数组内容。在这里,我正在使用HttpClient发送多部分表单数据。边界自动生成。希望能帮助到你。

using (var client = new HttpClient())
{
    MultipartFormDataContent form = new MultipartFormDataContent();
    var uri = new StringBuilder(_domain).Append("/api/data/send");
    client.Timeout = Timeout.InfiniteTimeSpan;

    //adding all properties to the form
    if (!String.IsNullOrEmpty(model.SenderAddress))
        form.Add(new StringContent(model.SenderAddress), "SenderAddress");  
    if (model.Attachments.FirstOrDefault() != null)
    {
        foreach (var attachment in model.Attachments)
        {
            byte[] fileData = null;
            using (var binaryReader = new BinaryReader(attachment.InputStream))
            {
                fileData = binaryReader.ReadBytes(attachment.ContentLength);
            }
            form.Add(new ByteArrayContent(fileData, 0, fileData.Length), "Attachments", attachment.FileName);
         }
     }

    HttpResponseMessage response = await client.PostAsync(uri.ToString(), form);

    response.EnsureSuccessStatusCode();
    string result = response.Content.ReadAsStringAsync().Result;

    if (response.StatusCode == HttpStatusCode.OK)
        return Request.CreateResponse(response.StatusCode, "Successfully Sent!");
    else
        return Request.CreateResponse(response.StatusCode, result);          
}

答案 2 :(得分:0)

想通了

    public void Run() {
        MultipartContent h = new MultipartContent("batching", "77f2569d");
        HttpContent content1 = new ByteArrayContent(Encoding.UTF8.GetBytes(data));
        h.Add(content1);
        Task<string> response = PostAsync2("https://server/ucwa/oauth/v1/applications/10751539691/batch", "Bearer", "cwt=AAEBHAEFAAAAAAAFFQAAACd5t5mMpiIgog-06W0EAACBEJH-LcfxNO5SsZ3Ya9NHaRuCAluYgyChwp4HzFpww_sZkaK5SBFBUY4Uk3oW6u6U0Oeh9jWOZoYI8fwX34ce1ggNEJH-LcfxNO5SsZ3Ya9NHaRs", h, "multipart/batching");
        response.Wait();
        string result = response.Result;
    }

    public static async Task<string> PostAsync2(string uri, string token_type, string access_token, HttpContent postData, string accept)
    {
        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uri)
        {
            Content = postData // CONTENT-TYPE header
        };
        // new StringContent(postData, Encoding.UTF8, content_type)

        if (accept != null) request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(accept)); // ACCEPT header
        if (token_type != null && access_token != null) request.Headers.Authorization = new AuthenticationHeaderValue(token_type, access_token);
        HttpResponseMessage g = await client.SendAsync(request);

        if (g.IsSuccessStatusCode)
        {
            return await g.Content.ReadAsStringAsync();
        }
        else
        {
            return null;
        }
    }

答案 3 :(得分:-1)

尝试将标题与内容分开设置。

var httpClient = new HttpClient();
var body = new StringContent(bodycontent);
body.Headers.ContentType = new MediaTypeHeaderValue("multipart/batching;boundary=77f2569d");
var response = await httpClient.PostAsync(url, body);

答案 4 :(得分:-1)

 public async void  newPostAsync(String json)
   {

   endPoint = w3+"accounts/" + account + "/orders";
   HttpClient client = new HttpClient();
   client.DefaultRequestHeaders.Add("Authorization", token_type + " " + access_token);
        var jsonpack = new StringContent(json, Encoding.UTF8, "application/json");
        client.DefaultRequestHeaders.Accept.Add(new 
  System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            var response = await client.PostAsync(endPoint, jsonpack);
            responseString = await response.Content.ReadAsStringAsync();



        }
        catch (Exception io)
        {
            Console.WriteLine("" + io.Message);
        }

        return responseString;


    }

先验是一个示例,但是它使用json而不是批处理,但是:

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://server/ucwa/oauth/v1/applications/10751539691/batch")
        {
            Content = new StringContent("", Encoding.UTF8, "multipart/batching;boundary=77f2569d") // CONTENT-TYPE header
        };

内容在等号之前应有一个变量名,并且您应该使用

 Content content= new StringContent("", Encoding.UTF8, "multipart/batching") // CONTENT-TYPE header

边界的标头不同,您会从分号中获取格式错误

相关问题