我正在尝试创建一个与Assembla API进行通信的工具,但我无法正确进行身份验证。我使用了here所述的3步骤程序。 检索PIN码现在没有问题,但我确实希望将来更加智能化。我无法更换PIN码以获取持票人令牌。
我的代码原样:
private void button1_Click(object sender, EventArgs e)
{
var url = string.Format("https://api.assembla.com/token");
var web = (HttpWebRequest)WebRequest.Create(url);
web.Method = "POST";
//web.Accept = "application/x-www-form-urlencoded";
web.ContentType = "application/x-www-form-urlencoded";
web.Headers["client_id"] = "xxxxx";
web.Headers["client_secret"] = "xxxxxx";
var data = string.Format("grant_type=pin_code&pin_code={0}", textBox1.Text);
byte[] buffer = Encoding.UTF8.GetBytes(data);
web.ContentLength = buffer.Length;
var postData = web.GetRequestStream();
postData.Write(buffer, 0, buffer.Length);
postData.Close();
WebResponse resp = web.GetResponse();
var sr = new StreamReader(resp.GetResponseStream());
var result = sr.ReadToEnd().Trim();
}
这会导致网络请求异常:The remote server returns an error: (400) Bad Request.
行WebResponse resp = web.GetResponse();
我不确定如何获取有关错误的更多信息。但是,如果我使用http://requestmaker.com/填写我的凭据和密码,它会返回相同的错误代码以及回复正文{"error":"invalid_request","error_description":"'client_id' required."}
。我尝试使用client_id作为标题并使用硬编码在Assembla" https://_client_id:_client_secret@api.assembla.com/token?grant_type=pin_code&pin_code=_pin_code
"的示例中进行硬编码。两者都返回相同的结果。
这是我第一次使用http请求做任何事情,所以对我来说可能是一些愚蠢的概述。 错误可能是Assembla特定的,但如果有人在我的代码中发现任何明显的错误,我会感谢您提供纠正建议。
答案 0 :(得分:0)
有一个或多或少完整的API in this answer用于交换访问令牌的PIN。该API用于通过OAuth获取imgUr帐户上传令牌。部分相关功能:
// the PIN previously received
string myPin = "";
private bool RequestToken(string CliId, string CliSecret)
{
// request format as per imgUR API - YMMV
string sReq = string.Format("client_id={0}&client_secret={1}&grant_type=pin&pin={2}",
CliId, CliSecret, myPin);
string url = "https://api.imgur.com/oauth2/token/";
bool myResult = true;
// create request for the URL, using POST method
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
// convert the request, set content format, length
byte[] data = System.Text.Encoding.UTF8.GetBytes(sReq);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
// write the date to request stream
Stream dstream = request.GetRequestStream();
dstream.Write(data, 0, data.Length);
dstream.Close();
// ToDo:
// GetResponse() in Try/Catch
// if there is an exception get the exact error
// otherwise:
// read the stream and parse (json) the result to get access token
return myResult;
}
与您拥有的内容没有太大区别,但它们都与格式化请求和提交请求有关。至少对于imgUr,文档非常具体地说明了请求字符串的外观,因此请针对您尝试访问的任何网站的文档进行双重检查。
请注意,在大多数情况下,结果是json,需要对其进行解析以获取令牌。