Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 向ebay API发送JSON请求_C#_Json_Ebay Api - Fatal编程技术网

C# 向ebay API发送JSON请求

C# 向ebay API发送JSON请求,c#,json,ebay-api,C#,Json,Ebay Api,好的,所以我在将这些JSON请求传递到Ebay API时遇到了一些麻烦 以下是json请求: string jsonInventoryRequest = "{" + "\"requests\": ["; int commaCount = 1; foreach (var ep in productsToProcess) { jsonInventoryRequest += "{\"off

好的,所以我在将这些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 += 
            "]" +
        "}";
以下是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,原因短语:“未经授权”, 版本: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-VERSION: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;域=.ebay.com;路径=/
WWW认证:基本内容长度:77内容类型: 应用程序/json}


有人能看出我错在哪里吗。干杯

好,因此身份验证失败,因为我发送了错误的身份验证令牌。需要从应用程序令牌获取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();
            }
        }

我们是在2018年。JSON解析器和格式化程序已经存在多年了。您不应该手动编写JSON,永远不要。也就是说,您的问题在于身份验证方面,而不是发送的JSON。您好@CamiloTerevinto谢谢您的帮助。我还在学习,所以我不知道怎么做。手边有个例子。是的,我认为这是身份验证中的一个错误,但我的凭据是正确的,从我所看到的情况来看,我做的一切都是正确的。如果我能找到一个例子,那就太好了。如果你能停止在标题中添加语言标签,那就太好了。它们只是噪音,不做任何解释“问题”Ok@Proputix将尝试记住,下一次401表示您未经授权/认证。我猜您的请求甚至在读取json负载之前就被拒绝了。您应该使用库(例如JSON.Net)来处理JSON。
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();
            }
        }