我需要在wordpress管理面板中以編程方式執行一些操作,但無法管理如何使用C#和HttpWebRequest登錄到Wordpress。如何以編程方式登錄wordpress?
這裏是我做的:
private void button1_Click(object sender, EventArgs e)
{
string url = "http://localhost/wordpress/wp-login.php";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookies = new CookieContainer();
SetupRequest(url, request, cookies);
//request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
//request.Headers["Accept-Language"] = "uk,ru;q=0.8,en-us;q=0.5,en;q=0.3";
//request.Headers["Accept-Encoding"] = "gzip,deflate";
//request.Headers["Accept-Charset"] = "windows-1251,utf-8;q=0.7,*;q=0.7";
string user = "test";
string pwd = "test";
request.Credentials = new NetworkCredential(user, pwd);
string data = string.Format(
"log={0}&pwd={1}&wp-submit={2}&testcookie=1&redirect_to={3}",
user, pwd,
System.Web.HttpUtility.UrlEncode("Log In"),
System.Web.HttpUtility.UrlEncode("http://localhost/wordpress/wp-admin/"));
SetRequestData(request, data);
ShowResponse(request);
}
private static void SetupRequest(string url, HttpWebRequest request, CookieContainer cookies)
{
request.CookieContainer = cookies;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; uk; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)";
request.KeepAlive = true;
request.Timeout = 120000;
request.Method = "POST";
request.Referer = url;
request.ContentType = "application/x-www-form-urlencoded";
}
private void ShowResponse(HttpWebRequest request)
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
responseTextBox.Text = (((HttpWebResponse)response).StatusDescription);
responseTextBox.Text += "\r\n";
StreamReader reader = new StreamReader(response.GetResponseStream());
responseTextBox.Text += reader.ReadToEnd();
}
private static void SetRequestData(HttpWebRequest request, string data)
{
byte[] streamData = Encoding.ASCII.GetBytes(data);
request.ContentLength = streamData.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(streamData, 0, streamData.Length);
dataStream.Close();
}
但不幸的是在性反應,我得到的登錄頁面的唯一HTML源代碼,似乎cookie不包含會話ID。我在該代碼之後執行的所有請求也返回登錄頁面的HTML源,因此我可以認爲它不能正確登錄。
任何人都可以幫助我解決這個問題或給工作的例子嗎?
我想實現的主要目標是在Nextgen Gallery插件中爲Wordpress掃描新圖像。有XML-RPC的方式嗎?
在此先感謝。
某些代碼不會是壞的其他人們也許正在尋找解決方案(像我一樣)。多數民衆贊成在一個論壇... – C4u 2015-03-14 17:46:22
如此殘酷!爲什麼解決方案不在那裏? – 2015-08-27 04:36:47
這是公認的答案?沒有代碼? – DidIReallyWriteThat 2016-11-06 00:44:29