项目中需要使用GitHub 的restful API来fork, commit, pull request.
在使用HttpWebRequest来Post请求时设置了正确的Header和Body但是返回403Forbidden错误
解决方案:增加获取身份验证信息
httpRequest.UserAgent = "Code Sample Web Client"
GitHub for API: https://developer.github.com/v3/repos/forks/#create-a-fork
public static async Task PullRequestAsync()
{
string url_fork = @"https://api.github.com/repos/OWNERNAME/REPO_YOU_WANT/forks";
string res = Post(url_fork, "");//如果是organization调用需要加参数
Console.WriteLine(res);
}
public static string Post(string url, string content)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
//req.Headers.Add("ContentType", "application/vnd.github.v3+json");
req.Headers.Add("Authorization", "token *********");
req.UserAgent = "Code Sample Web Client";
//byte[] data = Encoding.UTF8.GetBytes(content);
//req.ContentLength = data.Length;
//using (Stream reqStream = req.GetRequestStream())
//{
// reqStream.Write(data, 0, data.Length);
// reqStream.Close();
//}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
在项目中通过GitHub RESTful API进行fork、commit和pull request操作时,遇到使用HttpWebRequest发送POST请求返回403 Forbidden的问题。经过分析,问题出在身份验证上。解决方案是设置UserAgent属性,例如:httpRequest.UserAgent = "Code Sample Web Client"。确保遵循GitHub API的授权规定。
4196

被折叠的 条评论
为什么被折叠?



