在这篇,我就利用C#写一个小程序,翻译: 思路是这样的: 1:发送POST(或者GET) 2:获取POST(或者GET)的响应 3:正则匹配我们想要的值。 发生POST(或者GET)的函数:
复制代码 代码如下: public static string GetGetRequest(string urlP,string encode){ if(null==urlP) return null; string StrRetP = null; Stream dataStream = null; try{ HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create(urlP); myHttpWebRequest.Timeout = 10000; // 10 secs HttpWebResponse Objresponse =(HttpWebResponse)myHttpWebRequest.GetResponse(); //Encoding enc = Encoding.GetEncoding(1252); // Windows default Code Page if(Objresponse.StatusDescription == "OK"){//HttpStatusCode.OK dataStream = Objresponse.GetResponseStream (); Encoding objE = String.IsNullOrEmpty(encode)?Encoding.GetEncoding(0):Encoding.GetEncoding(encode); StreamReader r = new StreamReader(dataStream,objE); StrRetP= r.ReadToEnd(); } }catch(Exception e){ StrRetP =e.Message; }finally{ if(null!=dataStream) dataStream.Close(); } return StrRetP; }
这个我在前面的一些文章中有所介绍。 然后正则匹配的函数:
复制代码 代码如下: public static string GetMatchString(string text,string pattern,int point){ if(String.IsNullOrEmpty(text)||String.IsNullOrEmpty(pattern))return String.Empty; Regex rx = new Regex(pattern,RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline); Match match = rx.Match(text); string word=""; if (match.Success) word = match.Groups[point].Value; return word.Trim(); }
这个数根据一个正则表达数,返回匹配的值。 直接进入Main主体:
复制代码 代码如下: public static void Main(string[] args){ string mess ="我们"; Console.WriteLine(HttpUtility.UrlEncode("我们")); mess = GetGetRequest("http://translate.google.com/translate_t?langpair="+HttpUtility.UrlEncode("zh-CN|en")+ "&text="+HttpUtility.UrlEncode(mess,System.Text.UnicodeEncoding.GetEncoding( "Gb2312")),"utf-8"); //Console.WriteLine(mess); mess = GetMatchString(mess,@"(<div id=result_box dir=""ltr"">)([?:sS]*?)(</div>)",2); Console.WriteLine(mess); }
注意的是 HttpUtility.UrlEncode(mess,System.Text.UnicodeEncoding.GetEncoding( "Gb2312")) 这句,无法识别UrlEncode的字符编码,这里需要指明。 OK,然后csc了,编译一下,下载一下吧。
(编辑:焦作站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|