3

我正在尝试使用 Google Checkout,但在发布到结帐服务器时遇到问题。这是我的代码:

XNamespace ns = XNamespace.Get("http://checkout.google.com/schema/2");

XDocument cart = new XDocument();
XElement rootElement = new XElement(ns + "checkout-shopping-cart",
    new XElement("shopping-cart",
        new XElement("items",
            new XElement("item",
                new XElement("item-name", "doodad"),
                new XElement("item-description", "Description for the doodad"),
                new XElement("unit-price", 9.99, new XAttribute("currency", "GBP")),
                new XElement("quantity", 1)
            )
         )
    )
);

cart.Add(rootElement);

string authKey = "111222333444:NOTAREALKEY";
authKey = EncodeToBase64(authKey);

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://checkout.google.com/cws/v2/Merchant/111222333444/merchantCheckout");

request.Method = "POST";
byte[] byteArray = Encoding.UTF8.GetBytes(cart.ToString());
request.ContentType = "application/xml; charset=UTF-8";
request.ContentLength = byteArray.Length;
request.Headers.Add("Authorization: Basic " + authKey);
request.Accept = "application/xml; charset=UTF-8";

Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();

HttpWebResponse response = (HttpWebResponse)request.GetResponse(); // Exception here!
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseText = reader.ReadToEnd();

reader.Close();
dataStream.Close();
response.Close();

当我调用 GetResponse() 时,我得到一个(400) Bad Request.

对此的任何帮助将不胜感激。

4

3 回答 3

4

正如 Jon Skeet 指出的那样,您的 XML 看起来很糟糕:-)。为了进一步帮助调试 - 响应中可能有更多关于错误的信息。WebException有一个Response对象,它可能有更详细的错误消息,可以通过调用其GetResponseStream()方法来读取。

于 2010-01-27T14:47:45.987 回答
2

对 Google Checkout API 一无所知,您确定不需要每个元素上的命名空间吗?

XElement rootElement = new XElement(ns + "checkout-shopping-cart",
    new XElement(ns + "shopping-cart"),
        new XElement(ns + "items",
                     // etc

这当然是Checkout API 指南向我建议的 - 请注意,“xmlns=...”意味着这是该元素和所有后代元素的命名空间,除非另有说明。

于 2010-01-27T14:10:32.157 回答
0

如果异常是 WebException,您仍然可以阅读响应消息。这将为您提供有关问题所在的更多信息:

try {
   response = (HttpWebResponse)request.GetResponse();
}
catch (WebException ex1) {
   response = ex1.Response();
}
于 2010-03-24T20:35:21.583 回答