GetResponse抛出400错误请求

本文关键字:请求 错误 抛出 GetResponse | 更新日期: 2023-09-27 17:58:07

Getting 400 bad Request当尝试从HTTPS post请求中获取响应时。这是我的代码:

try
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://coupons.valassis.eu/capi/directPrint/"+offerID);
    httpWebRequest.Credentials = new NetworkCredential(userName,Password);
    WebHeaderCollection myWebHeaderCollection = httpWebRequest.Headers;
    myWebHeaderCollection.Add("Authorization: Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(httpWebRequest.Credentials.ToString())));
    myWebHeaderCollection.Add("x-valassis-country-code: uk");
    httpWebRequest.ContentType = "application/json";
    httpWebRequest.Accept = "application/json";
    httpWebRequest.Method = "POST";
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        string json = "[{ '"consumerId'": '"000000000000001'", '"remoteConsumerId'": '"000000000000001'" , '"Barcode'": '"Itf: 04910033400000000000000001,Ean13:ccode'", '"Type'": '"j'", '"returnUrl'": '"http://www.durex.co.uk'",'"CouponDescription'" : '"Coupon For:'"" + this.FirstName + " " + this.SurName + "'" }]";
        var serializer = new JavaScriptSerializer();
        streamWriter.Write(json);
        streamWriter.Flush();
        streamWriter.Close();
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (Stream streamReader =httpResponse.GetResponseStream())
        {
            using (StreamReader r = new StreamReader(streamReader))
            {
                var result = r.ReadToEnd();    
            }
        }
    }        
}
catch (WebException e)
{
}

有人知道问题出在哪里吗?或者如何解决这个问题?

GetResponse抛出400错误请求

您创建的JSON字符串无效,因为CouponDescription属性包含奇数个引号。

如果我运行这个。。。。

    var FirstName = "Joe";
var SurName = "Bloggs";
var json = "[{ '"consumerId'": '"000000000000001'", '"remoteConsumerId'": '"000000000000001'" , '"Barcode'": '"Itf: 04910033400000000000000001,Ean13:ccode'", '"Type'": '"j'", '"returnUrl'": '"http://www.durex.co.uk'",'"CouponDescription'" : '"Coupon For:'"" + FirstName + " " + SurName + "'" }]";

我明白。。。

[{ "consumerId": "000000000000001", "remoteConsumerId": "000000000000001" , "Barcode": "Itf: 04910033400000000000000001,Ean13:ccode", "Type": "j", "returnUrl": "http://www.durex.co.uk","CouponDescription" : "Coupon For:"Joe Bloggs" }]

查看CouponFor值,引号未闭合。

像LINQPad和JSONLint这样的工具对于验证这些场景中的代码片段非常有用