2014-04-14 63 views
-1

獲取400錯誤請求嘗試從我的HTTPS發佈請求獲取響應時。這裏是我的代碼:GetResponse拋出400錯誤請求

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) 
{ 

} 

任何人都知道可能是什麼問題?或者如何解決這個問題?

回答

1

您創建的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值,引號沒有關閉。

LINQPadJSONLint這樣的工具對於驗證這些場景中的代碼片段非常有用