我正在努力開發一個C#類來登錄到Web主機(Hostgator)上的cPanel。無法用C#WebRequest登錄到cPanel
在PHP這是很容易使用curl擴展如下:
$url = "http://mysite.com:2082/";
$c = curl_init($url);
curl_setopt($c, CURLOPT_USERPWD, 'user:password');
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($c);
if ($result === false)
$result = curl_error($c);
curl_close($c);
file_put_contents('log.txt', $result);
//print_r($result);
現在,這裏是我的C#類的各種嘗試,使其工作註釋掉:
class HTTPHandler
{
public static string Connect (string url, string userName, string password)
{
string result;
try
{
// An initial @ symbol in the password must be escaped
if (password.Length > 0)
if (password[0] == '@')
password = "\\" + password;
// Create a request for the URL.
WebRequest request = WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = new NetworkCredential(userName, password);
/*
var credCache = new CredentialCache();
credCache.Add(new Uri(url), "Basic",
new NetworkCredential(userName, password));
request.Credentials = credCache;
*/
//request.Method = "POST";
//request.ContentType = "application/x-www-form-urlencoded";
/*
// Create POST data and convert it to a byte array.
string postData = string.Format("user={0}&pass={1}", userName, password);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
*/
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Display the content.
result = string.Format("Server response:\n{0}\n{1}", response.StatusDescription, reader.ReadToEnd());
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception e)
{
result = string.Format("There was an error:\n{0}", e.Message);
}
return result;
}
}
}
但我一直在GetResponse階段收到錯誤401(未授權)。
當我比較我的本地主機測試頁中的PHP和C#提交之間的$ _SERVER變量時,除了發送端口有點不同之外,我獲得了相同的數據。關鍵的PHP_AUTH_USER和PHP_AUTH_PW是相同的。
我的操作系統是Windows 7 64位和我使用的Visual C#2010
我猜的解決方案是非常簡單的,但到目前爲止,我感到莫名其妙。但是C#的相對新手。我希望有人能幫忙。
謝謝您的回答。使用本地服務器上的測試頁面,我沒有使用PreAuthenticate接收用戶名和密碼的詳細信息到PHP頁面。和Curl一起,我不需要使用cookies。我發現在使用PHP和Curl連接到cPanel之前,我不得不跳過最初的@字符。 – Andy
@好的,但你有嘗試過嗎? –
希望有Linux主機與cPanel的人可以測試一些成功登錄的C#代碼。它與Cookie無關,因爲您必須使其通過GetResponse階段而沒有錯誤。只需模擬我的PHP示例。 – Andy