将链接提交给搜索引擎
起因
前一段时间,在百度站长工具中,看到可以将URL主动推送给搜索引擎,便于搜索引擎收录,看看c#怎么实现,其实就是通过HTTP的POST将数据提交给搜索引擎.主要实现了百度和必应搜索引擎的主动推送.在加入博客之前,先用winfrom写一个简单的demo.
百度推送
string url = string.Format("http://data.zz.baidu.com/urls?site={0}&token={1}", "自己的域名(不带http)", "百度的密钥");
//上面有2个参数
//1 指定站点 如:www.qiufengblog.com
//2 百度站长平台的密钥,自己申请
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
var buffer = Encoding.UTF8.GetBytes(txtUrl); //将要提交的url转成byte数组,放到请求里
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "text/plain";
httpWebRequest.ContentLength = buffer.Length;
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(buffer, 0, buffer.Length);
stream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream()))
{
string json = reader.ReadToEnd();
dynamic result = JToken.Parse(json) as dynamic;
tips += result.success > 0 ? "百度推送成功!" : "百度推送失败!";
tips += Environment.NewLine;
}
}
必应推送
var obj = new { siteUrl = "www.qiufengblog.com", url = txtUrl };
var buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj)); //匿名类属性为siteUrl和url,转为json,在转为byte数组
string bingURL = string.Format("https://ssl.bing.com/webmaster/api.svc/json/{0}?apikey={1}", "SubmitUrl", "必应的密钥");
//上面字符串拼接要2个参数
//1. 必应还提供很多api可以使用,因为只是将URL推送给必应搜索引擎,只用SubmitUrl
//2. 必应的密钥
//具体可以参考:https://msdn.microsoft.com/en-us/library/jj572365
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(bingURL);
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { return true; };
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/json;charset=utf-8"; //必应要指定提交的数据格式为json
httpWebRequest.ContentLength = buffer.Length;
Stream stream = httpWebRequest.GetRequestStream();
stream.Write(buffer, 0, buffer.Length);
stream.Close();
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse.StatusCode == HttpStatusCode.OK)
{
using (StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream()))
{
string json = reader.ReadToEnd();
dynamic result = JToken.Parse(json) as dynamic;
tips += result.d == null ? "必应推送成功!" : "必应推送失败!";
tips += Environment.NewLine;
}
}
简单测试
秋风
2018-09-05