gpt4 book ai didi

c# - 为什么我在发布到 Google Reader API 时收到 401(未经授权)错误?

转载 作者:可可西里 更新时间:2023-11-01 17:16:11 25 4
gpt4 key购买 nike

我正在尝试使用来自 this page 的信息与 Google 阅读器(未记录/非官方)API 交互.我的第一步是获取 SID 和 token ,这工作正常,但我似乎无法在不收到 401 错误的情况下发布任何内容。

这是我用来获取我的 SID 和 token 的代码:

static string getSid()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.google.com/accounts/ClientLogin?service=reader&Email=username&Passwd=password");
req.Method = "GET";
string sid;

HttpWebResponse response = (HttpWebResponse)req.GetResponse();
using (var stream = response.GetResponseStream())
{
StreamReader r = new StreamReader(stream);
string resp = r.ReadToEnd();

int indexSid = resp.IndexOf("SID=") + 4;
int indexLsid = resp.IndexOf("LSID=");
sid = resp.Substring(indexSid, indexLsid - 5);

return sid;
}
}

并生成 cookie 并获取 token :

    static Cookie getCookie(string sid)
{
Cookie cookie = new Cookie("SID", sid, "/", ".google.com");
return cookie;
}

static string getToken(string sid, Cookie cookie)
{
string token;
string url = "http://www.google.com/reader/api/0/token";

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = new CookieContainer();
req.CookieContainer.Add(cookie);

HttpWebResponse response = (HttpWebResponse)req.GetResponse();
using (var stream = response.GetResponseStream())
{
StreamReader r = new StreamReader(stream);
token = r.ReadToEnd();
return token;
}
}

现在,如果我尝试使用以下内容执行 POST(在此示例中,插入一个新标签),我会收到 401 错误。

    static void insertTag(string tag, Cookie cookie)
{
string result = "";
string data = Uri.EscapeDataString("a="+tag+"&T=" + Program.token);

byte[] buffer = Encoding.GetEncoding(1252).GetBytes(data);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create
("http://www.google.com/reader/api/0/edit-tag?client=-");
WebReq.Method = "POST";

WebReq.Credentials = new NetworkCredential("username", "password");


WebReq.ContentType = "application/x-www-form-urlencoded";
WebReq.ContentLength = buffer.Length;

Stream PostData = WebReq.GetRequestStream();

PostData.Write(buffer, 0, buffer.Length);
PostData.Close();

HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
result = _Answer.ReadToEnd();

if (result.Length < 0)
result = "";
}

错误发生在行 Stream Answer = WebResp.GetResponseStream();

最佳答案

您需要仔细检查您是否设置了用户代理。我之前没有设置它时遇到过同样的问题。

例如:

WebClient client = new WebClient();

client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

或:MSDN Link

myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.UserAgent="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";

关于c# - 为什么我在发布到 Google Reader API 时收到 401(未经授权)错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1275493/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com