【问题标题】:Sending a JSON request to ebay API向 ebay API 发送 JSON 请求
【发布时间】:2018-01-29 00:12:24
【问题描述】:

好的,所以我在将这些 JSON 请求通过 Ebay API 时遇到了一些麻烦。

这里是json请求:

string jsonInventoryRequest = "{" +
                    "\"requests\": [";

        int commaCount = 1;
        foreach (var ep in productsToProcess)
        {
            jsonInventoryRequest += "{\"offers\": [{" +
                "\"availableQuantity\":" + ep.EbayProductStockQuantity + "," +
                "\"offerId\":\"" + ep.EbayID.ToString() + "\"," +
                "\"price\": {" +
                    "\"currency\": \"AUD\"," +
                    "\"value\":\"" + ep.EbayProductPrice.ToString() + "\"" +
                "}" +
            "}],";

            jsonInventoryRequest += "\"shipToLocationAvailability\": " + "{" +
                "\"quantity\":" + ep.EbayProductStockQuantity +
                "},";

            jsonInventoryRequest += "\"sku\": " + ep.EbayProductSKU.ToString() + "}";
            if (commaCount < productsToProcess.Count())
                jsonInventoryRequest += ",";

            commaCount++;
            sendEbayApiRequest = true;
        }

        jsonInventoryRequest += 
            "]" +
        "}";

而上述 JSON 请求的Debug.WriteLine() 输出为:

json string = {"requests": [{"offers": [{"availableQuantity":0,"offerId":"098772298312","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":0},"sku": 135779},{"offers": [{"availableQuantity":1,"offerId":"044211823133","price": {"currency": "AUD","value":"148.39"}}],"shipToLocationAvailability": {"quantity":1},"sku": 133607}]}

这是发送请求的 C# 代码:

var ebayAppIdSetting = _settingService.GetSettingByKey(
                            "ebaysetting.appid", "");

        var ebayCertIdSetting = _settingService.GetSettingByKey(
                            "ebaysetting.certid", "");

        var ebayRuNameSetting = _settingService.GetSettingByKey(
                            "ebaysetting.appid", "");

        var stringToEncode = ebayAppIdSetting + ":" + ebayCertIdSetting;

        HttpClient client = new HttpClient();
        byte[] bytes = Encoding.UTF8.GetBytes(stringToEncode);
        var base64string = "Basic " + System.Convert.ToBase64String(bytes);
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);

        var stringContent = "?grant_type=client_credentials&" + "redirect_uri=" + ebayRuNameSetting + "&scope=https://api.sandbox.ebay.com/oauth/api_scope";
        var requestBody = new StringContent(stringContent.ToString(), Encoding.UTF8, "application/json");
        requestBody.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
        var response = client.PostAsync("https://api.sandbox.ebay.com/identity/v1/oauth2/token", requestBody);

当我执行Debug.WriteLine("response.Content = " + response.Result); 时得到的输出是:

response.Content = StatusCode: 401, ReasonPhrase: 'Unauthorized', 版本:1.1,内容:System.Net.Http.StreamContent,标题:{
RlogId: t6ldssk%28ciudbq%60anng%7Fu2h%3F%3Cwk%7Difvqn*14%3F0513%29pqtfwpu%29pdhcaj%7E%29fgg%7E%606%28dlh-1613f3af633-0xbd X-EBAY-C-REQUEST-ID:ri=HNOZE3cmCr94,rci=6kMHBw5dW0vMDp8A
X-EBAY-C-版本:1.0.0 X-EBAY-REQUEST-ID: 1613f3af62e.a096c6b.25e7e.ffa2b377!/identity/v1/oauth2/!10.9.108.107!r1esbngcos[]!token.unknown_grant!10.9.107.168!r1oauth-envadvcdhidzs5k[] 连接:保持活动日期:2018 年 1 月 29 日星期一 00:04:44 GMT
设置 Cookie:ebay=%5Esbf%3D%23%5E;Domain=.ebay.com;Path=/
WWW-Authenticate:基本内容长度:77 内容类型: 应用程序/json }

谁能看到我哪里出错了。干杯

【问题讨论】:

  • 我们在 2018 年。JSON 解析器和格式化程序已经存在多年。您不应该手动编写 JSON,永远不要。也就是说,您的问题出在身份验证方面,而不是发送的 JSON。
  • 嗨@CamiloTerevinto 感谢您的帮助。我还在学习,所以我不知道该怎么做。有一个方便的例子。是的,我认为这是身份验证错误,但我的凭据是正确的,而且我已经完成了我所看到的一切。如果我能找到一个例子就好了
  • 如果您停止在标题中添加语言标签也很好。他们只是噪音,没有解释“问题”
  • 好的,@Plutonix 下次会尝试记住这一点
  • 401 表示您未获得授权/身份验证。我猜您的请求甚至在读取 json 有效负载之前就被拒绝了。您应该使用库(例如 JSON.Net)来处理您的 json。

标签: c# json ebay-api


【解决方案1】:

好的,因此身份验证失败,因为我发送了错误的身份验证令牌。需要从应用令牌中获取 oauth 令牌。

所以不是像这样的base64编码令牌:

var base64string = "Basic " + System.Convert.ToBase64String(bytes);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", base64string);

我需要做以下事情:

url = "https://api.sandbox.ebay.com/sell/inventory/v1/bulk_update_price_quantity";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.Method = "POST";
        //request.ContentType = "application/json; charset=utf-8";
        request.Headers.Add("Authorization", "Bearer **OAUTH TOKEN GOES HERE WITHOUT ASTERIKS**");

        // Send the request
        using (var streamWriter = new StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(jsonInventoryRequest);
            streamWriter.Flush();
            streamWriter.Close();
        }

        // Get the response
        HttpWebResponse response = (HttpWebResponse) request.GetResponse();
        if (response != null)
        {
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                // Parse the JSON response
                var result = streamReader.ReadToEnd();
            }
        }

【讨论】:

    猜你喜欢
    • 2016-10-31
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 2018-06-02
    • 2019-03-29
    相关资源
    最近更新 更多