小黄鸡.Net版(Simsimi.Net)

    自从人人网小黄鸡火了以后,我一直在研究.Net版的小黄鸡。首先感谢cubernethttp://my.csdn.net/cubernet)给出了C#版本的Simsim,作为参考,我改写出了VB.Net版的Simsimi。原理很简单,网上一大堆,但是我自己弄起来问题还是很多。我自己改写的一个类文件如下:

Imports System.Net
Imports System.IO
Imports System.Text
Imports System.IO.Compression
Imports System.Reflection
Imports System.Collections.Generic
Public Class Simsimi
    Public Function getcookie() As String
        Dim Cookiesstr As String = Nothing
        Dim cookies As CookieCollection = New CookieCollection()
        Dim request As HttpWebRequest = Nothing
        request = WebRequest.Create("http://www.simsimi.com/talk.htm")
        request.CookieContainer = New CookieContainer()
        request.CookieContainer.Add(cookies)
        Dim response As HttpWebResponse = request.GetResponse()
        Cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri)
        Return Cookiesstr
    End Function
    Public Function showmsg(ByVal q As String, ByVal cookie As String)
        Dim ans As String = ""
        Dim url As String = String.Format("http://www.simsimi.com/func/req?msg={0}&lc=ch", q)
        Dim request As HttpWebRequest = Nothing
        Try
            request = WebRequest.Create(url)
            request.Method = "GET"
            request.KeepAlive = True
            request.ServicePoint.Expect100Continue = False
            request.Accept = "application/json,text/javascript,*/*;q=0.01"
            request.Headers.Add("Accept-Language", "zh-cn")
            request.Headers.Add("Accept-Encoding", "gzip,deflate")
            request.Headers.Add("Cookie", cookie)
            request.Referer = "http://www.simsimi.com/talk.htm"
            request.UserAgent = "Mozilla/4.0(compatible;MSIE 7.0;Windows NT 6.1;Trident/5.0;SLCC2;.NET CLR 2.0.50727;.NET CLR 3.5.30729;.NET CLR 3.0.30729;.NET4.0C;.NET4.0E)"
            request.ContentType = "application/json;charset=utf-8"
            request.AllowAutoRedirect = False
            Dim response As HttpWebResponse = request.GetResponse()
            Dim sr As StreamReader = New StreamReader(response.GetResponseStream(), Encoding.UTF8)
            ans = sr.ReadToEnd()
            If ans <> "{}" Then
                ans = ans.Substring(ans.IndexOf(":") + 2, ans.IndexOf(",") - ans.IndexOf(":") - 3)
            End If
            request.Abort()
            response.Close()
        Catch ex As Exception
            ans = ex.Message
        End Try
        Return ans
    End Function
    但是,调用这个类会报错:服务器提交了协议冲突. Section=ResponseHeader Detail=CR 后面必须是 LF.代码没什么错,主要是由于:微软没有容忍不符合RFC 822中的httpHeader必须以CRLF结束的规定的服务器响应。解决办法呢?可以参考这里:http://blog.csdn.net/mingwar/article/details/5870431。作者在原来的程序中是这样写的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Reflection;
namespace 小贱鸡
{
    class simsimi
    {
        public static string GetCookie()
        {
            string Cookiesstr = null;
            CookieCollection cookies = new CookieCollection();
            HttpWebRequest request = null;
            request = (HttpWebRequest)WebRequest.Create("http://www.simsimi.com/talk.htm");
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(cookies);
            //Get the response from the server and save the cookies from the request..
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Cookiesstr = request.CookieContainer.GetCookieHeader(request.RequestUri);
            return Cookiesstr;
        }
        public static string Hi_Simsimi(string que, string cookies)
        {
            string ans = "我们换个话题吧";
            string url = String.Format("http://www.simsimi.com/func/req?msg={0}&lc=ch",que);
            HttpWebRequest hi_request = null;
            try
            {
                hi_request = (HttpWebRequest)WebRequest.Create(url);
                hi_request.Method = "GET";
                hi_request.KeepAlive = true;
                hi_request.ServicePoint.Expect100Continue = false;
                //终端信息
                hi_request.Accept = "application/json,text/javascript,*/*;q=0.01";
                hi_request.Headers.Add("Accept-Language", "zh-cn");
                hi_request.Headers.Add("Accept-Encoding", "gzip,deflate");
                hi_request.Headers.Add("Cookie", cookies);
                hi_request.Referer = "http://www.simsimi.com/talk.htm";
                hi_request.UserAgent = "Mozilla/4.0(compatible;MSIE 7.0;Windows NT 6.1;Trident/5.0;SLCC2;.NET CLR 2.0.50727;.NET CLR 3.5.30729;.NET CLR 3.0.30729;.NET4.0C;.NET4.0E)";
                hi_request.ContentType = "application/json;charset=utf-8";
                
                hi_request.AllowAutoRedirect = false;
                HttpWebResponse hi_response = (HttpWebResponse)hi_request.GetResponse();
                StreamReader sr = new StreamReader(hi_response.GetResponseStream(), Encoding.UTF8);
                ans = sr.ReadToEnd();
                if (ans != "{}")
                {
                    string[] substr = ans.Split(new char[] { '"' });
                    //从response中获取redirect URL
                    ans = substr[3];
                }
                hi_request.Abort();
                hi_response.Close();
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
                //return e.ToString();
                return "不好意思死鸡了⊙︿⊙重启下程序吧~";
            }
            
            return ans;
        }
        public static bool SetAllowUnsafeHeaderParsing20()
        {
            //Get the assembly that contains the internal class
            Assembly aNetAssembly = Assembly.GetAssembly(typeof(System.Net.Configuration.SettingsSection));
            if (aNetAssembly != null)
            {
                //Use the assembly in order to get the internal type for the internal class
                Type aSettingsType = aNetAssembly.GetType("System.Net.Configuration.SettingsSectionInternal");
                if (aSettingsType != null)
                {
                    //Use the internal static property to get an instance of the internal settings class.
                    //If the static instance isn't created allready the property will create it for us.
                    object anInstance = aSettingsType.InvokeMember("Section",
                      BindingFlags.Static | BindingFlags.GetProperty | BindingFlags.NonPublic, null, null, new object[] { });
                    if (anInstance != null)
                    {
                        //Locate the private bool field that tells the framework is unsafe header parsing should be allowed or not
                        FieldInfo aUseUnsafeHeaderParsing = aSettingsType.GetField("useUnsafeHeaderParsing", BindingFlags.NonPublic | BindingFlags.Instance);
                        if (aUseUnsafeHeaderParsing != null)
                        {
                            aUseUnsafeHeaderParsing.SetValue(anInstance, true);
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    }
}


    起初,我一直不理解最后这个函数,现在应该知道,这段程序的作用就是为了解决上面这个问题!

    最后,送上原作者的程序代码:

    http://download.csdn.net/detail/cubernet/5055633

    现在大家也可以玩玩小黄鸡了!

 

 

你可能感兴趣的:(.net)