转自:http://www.cnblogs.com/Joseph/articles/1620722.html
很多网站上嵌入Baidu/Google搜索功能。
说起来很简单,但在实现的时候总会遇到这样那样的问题。baidu/google搜索全英文是没任何问题的。
但搜索中文有小小麻烦。调用google搜索最简单,它会自动识别简繁及转换功能。但在百度搜索则行不通,这是我实现的时候遇到的小麻烦。
源代码:
/// <summary>
/// 调用百度搜索
/// </summary>
public class CBaiduSearcher
{
//搜索方法
public static void Search(Page page, string content)
{
string encode = page.Server.UrlEncode(content);
string hex = StrToHexStr(content);
string s = "http://www.baidu.com/s?ie=gb2312&bs=" + encode + "&wd=" + hex;
page.Response.Redirect(s, true);
}
//转换为16进制字符串
private static string StrToHexStr( string strString)
{
byte[] arrByte = System.Text.Encoding.GetEncoding("GB2312").GetBytes(strString);
string ret = string.Empty;
for ( int i = 0; i <= arrByte.Length - 1; i++)
ret = ret + "%" + Convert.ToString(arrByte[i], 16);
return ret;
}
}
/// 调用百度搜索
/// </summary>
public class CBaiduSearcher
{
//搜索方法
public static void Search(Page page, string content)
{
string encode = page.Server.UrlEncode(content);
string hex = StrToHexStr(content);
string s = "http://www.baidu.com/s?ie=gb2312&bs=" + encode + "&wd=" + hex;
page.Response.Redirect(s, true);
}
//转换为16进制字符串
private static string StrToHexStr( string strString)
{
byte[] arrByte = System.Text.Encoding.GetEncoding("GB2312").GetBytes(strString);
string ret = string.Empty;
for ( int i = 0; i <= arrByte.Length - 1; i++)
ret = ret + "%" + Convert.ToString(arrByte[i], 16);
return ret;
}
}
调用方法:
//调用百度搜索
protected void btnBaidu_Click( object sender, EventArgs e)
{
string src = txtSearch.Text;
CBaiduSearcher.Search( this.Page, src);
}
protected void btnBaidu_Click( object sender, EventArgs e)
{
string src = txtSearch.Text;
CBaiduSearcher.Search( this.Page, src);
}
//调用Google搜索
protected void btnGoogle_Click( object sender, EventArgs e)
{
string src = txtSearch.Text;
string web = "http://www.google.com/search?q=" + src;
Response.Redirect(web, true);
}
protected void btnGoogle_Click( object sender, EventArgs e)
{
string src = txtSearch.Text;
string web = "http://www.google.com/search?q=" + src;
Response.Redirect(web, true);
}