使用c#连接到web api

时间:2013-11-21 17:26:00

标签: c# .net

我正在尝试使用下面的代码进行身份验证,尽管我在尝试时获得了400的状态代码。任何建议,因为我不知道还有什么可以尝试?!我可以看到使用Fiddler的电话,但我已经没有想法了。 非常感谢

服务器返回以下错误消息:

代码段

        var httpWReq = (HttpWebRequest)WebRequest.Create("https://api5.silverpop.com/oauth/token");
        var postData = string.Format("&grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", config.ClientId, config.ClientSecret, config.RefreshToken);

                    // Also try this string but I get the same response
        //var postData = string.Format("?grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", config.ClientId, config.ClientSecret, config.RefreshToken);

        var encoding = new ASCIIEncoding();
        var data = encoding.GetBytes(postData);
        httpWReq.Method = "POST";
        httpWReq.ContentType = "x-www-form-urlencoded";
        httpWReq.ContentLength = data.Length;

        using (var stream = httpWReq.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)httpWReq.GetResponse();

        var result = new StreamReader(response.GetResponseStream()).ReadToEnd();

来自服务器的响应

The remote server returned an error: (400) Bad Request.

4 个答案:

答案 0 :(得分:3)

这似乎有效:

        var httpWReq = (HttpWebRequest)WebRequest.Create("https://api5.silverpop.com/oauth/token" + string.Format("?grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", clientId, clientSecret, refreshToken));
        var postData = "";

        var encoding = new ASCIIEncoding();
        var data = encoding.GetBytes(postData);
        httpWReq.Method = "POST";
        httpWReq.ContentType = "x-www-form-urlencoded";
        httpWReq.ContentLength = data.Length;

        using (var stream = httpWReq.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        var response = (HttpWebResponse)httpWReq.GetResponse();

        var result = new StreamReader(response.GetResponseStream()).ReadToEnd();

答案 1 :(得分:1)

尝试从

更改更改
var postData = string.Format("&grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", config.ClientId, config.ClientSecret, config.RefreshToken);

var postData = string.Format("?grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}", config.ClientId, config.ClientSecret, config.RefreshToken);

答案 2 :(得分:0)

这通常表示您以错误的方式联系服务器。你可能错过了一个'?'在你的帖子数据?

修改

尝试:

var client = new HttpClient();
var content = new FormUrlEncodedContent(<put content here>);
var response = await client.PostAsync("<your API URL>", content);

答案 3 :(得分:0)

如果您使用Fidler检查请求,您将在两种情况下都看到正文中的参数(使用前面的&amp;和前面的?符号)。

与&amp;标志: with & sign

随着?标志: with ? sign

正确的做法是删除?或者&amp;前面的符号然后是body中的参数名称将是grant_type。 有效的代码:

var postData = string.Format("grant_type=refresh_token&client_id={0}&client_secret={1}&refresh_token={2}",
            config.ClientId, config.ClientSecret, config.RefreshToken);