如何正确POST POST JSON数组以避免HTTP 400 Bad Request?

时间:2016-08-30 20:50:25

标签: c# json dotnet-httpclient

我有一个小型的C#应用​​程序,它使用HttpClient将JSON数组发布到在Java Jersey 2.0中实现的REST API。

我的客户端代码如下所示:

public class Customer {
  public string Name { get; set; }
  public string Address { get; set; }
}

Client.Customer customer1 = new Client.Customer {
  Name = "name 1", Address = "address 1"
};
Client.Customer customer2 = new Client.Customer {
  Name = "name 2", Address = "address 2"
};

List < Client.Customer > customerList = new List < Client.Customer > ();
customerList.Add(customer1);
customerList.Add(customer2);

string json = JsonConvert.SerializeObject(customerList);

EnvokeCreateCustomer("http://10.3.3.5:8080/", "jersey_test/webapi/customer", json).Wait();

static async Task EnvokeReadCustomer(string baseUrl, string apiUrl) {
  RestClient.Client restClient = new RestClient.Client();
  await restClient.ReadCustomer(baseUrl, apiUrl);
}

public async Task CreateCustomer(string baseUrl, string apiUrl, string customer) {
  using(var client = new HttpClient()) {
    client.BaseAddress = new Uri(baseUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Accept", "application/json");

    var response = await client.PostAsJsonAsync(apiUrl, customer);
    var p = response;
  }
}

当我运行此操作时,我收到HTTP 400错误请求。

当我对同一个API使用一个小的Python HttpClient代码时,运行正常:

import json
import urllib2

data = [{"name":"Customer 1", "address":"customer address 1"},
        {"name":"Customer 2", "address":"customer address 2"}]
payload = json.dumps(data)

req = urllib2.Request('http://10.3.3.5:8080/jersey_test/webapi/customer')
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(data))

我应该在C#代码中更改什么才能使此POST工作?

1 个答案:

答案 0 :(得分:1)

我建议您在FireFox中使用Inspect Element在Network部分中查看请求的标头。您应该添加一些其他标头。我认为吼叫者会做这个工作:

httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");