我正在用C#创建一个项目,以便从任何Facebook URL中获取一个Facebook ID。我有一个可以提供帮助的API,但是代码正在使用以下Ajax POST代码:
// get facebook id
$('#get-facebook-id').submit(function(event) {
$('#answer').html("<b>Working for you...</b>");
$.ajax({
type: 'POST',
url: 'https://codeofaninja.com/tools/get-facebook-id-answer.php',
data: $(this).serialize()
})
.done(function(data){
$('#answer').html(data);
$('#page_url_tb').val('')
})
.fail(function() {
alert( "Posting failed. Please try again." );
});
return false;
});
我正在尝试编写自己的代码,但给我一个错误。我的代码和下面的错误。
private string getFbAccountID(string facebookurl)
{
var request = (HttpWebRequest)WebRequest.Create("https://codeofaninja.com/tools/get-facebook-id-answer.php");
var postData = "page_url="+facebookurl;
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
错误:
<br />
<b>Notice</b>: Undefined index: page_url in <b>/home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/tools/get-facebook-id-answer.php</b> on line <b>3</b><br />
<br />
<b>Notice</b>: Undefined offset: 1 in <b>/home/100661.cloudwaysapps.com/rpxdhcedbx/public_html/tools/get-facebook-id-answer.php</b> on line <b>19</b><br />
<p>There was an error. Please try a different input.</p>
这总是给我这个错误。我希望有人可以帮助我
答案 0 :(得分:1)
我认为您正在研究this exercise。 :)
但是要回答您的问题,您不是使用URL编码facebookurl
。
如果您在其页面上使用示例Facebook URL之一,并使用浏览器(F12)中的开发人员工具查看网络流量,则将其视为正在发送的表单数据:page_url=https%3A%2F%2Fwww.facebook.com%2Fpages%2FAndrew-Garfield%2F166865773328160
>
jQuery的serialize()
函数为您做到了。
在C#中,您可以使用WebUtility.UrlEncode
:
var postData = "page_url=" + WebUtility.UrlEncode(facebookurl);
答案 1 :(得分:1)
这里您有使用System.Net.WebClient的替代方法,它将使您的代码更简洁:
private string getFbAccountID(string facebookurl)
{
using (var webClient = new System.Net.WebClient())
{
var formValues = new System.Collections.Specialized.NameValueCollection
{
{ "page_url", facebookurl }
};
var responseBytes = webClient.UploadValues(
"https://codeofaninja.com/tools/get-facebook-id-answer.php",
formValues
);
return System.Text.Encoding.UTF8.GetString(responseBytes);
}
}