Ejemplo n.º 1
0
        /// <summary>
        /// 执行API调用,返回结果数组
        /// </summary>
        /// <param name="script_name">调用的API方法,比如/v3/user/get_info, 参考 http://wiki.open.qq.com/wiki/API_V3.0%E6%96%87%E6%A1%A3 </param>
        /// <param name="param">调用API时带的参数</param>
        /// <param name="method">请求方法 post / get</param>
        /// <param name="protocol">协议类型 http / https </param>
        /// <returns>返回结果数组</returns>
        public RstArray Api(string script_name, Dictionary <string, string> param, string method, string protocol)
        {
            RstArray result_array = new RstArray();

            // 检查 openid 是否为空
            if (string.IsNullOrEmpty(param["openid"]))
            {
                result_array.Msg = "openid is empty";
                result_array.Ret = OPENAPI_ERROR_REQUIRED_PARAMETER_EMPTY;
                return(result_array);
            }
            // 检查 openid 是否合法
            if (!IsOpenId(param["openid"]))
            {
                result_array.Msg = "openid is invalid";
                result_array.Ret = OPENAPI_ERROR_REQUIRED_PARAMETER_INVALID;
                return(result_array);
            }
            // 无需传sig, 会自动生成
            if (param.ContainsKey("sig"))
            {
                param.Remove("sig");
            }

            // 添加一些参数
            param["appid"]  = appid.ToString();
            param["format"] = format;

            // 生成签名
            string secret = appkey + "&";
            string sig    = SnsSigCheck.MakeSig(method, script_name, param, secret);

            param.Add("sig", sig);

            string url = protocol + "://" + server_name + script_name;

            // 增加cookie
            Dictionary <string, string> cookie = new Dictionary <string, string>();

            //记录接口调用开始时间
            long start_time = SnsStat.GetTime();

            //通过调用以下方法,可以打印出最终发送到openapi服务器的请求参数以及url,不打印可以注释
            PrintRequest(url, param, method);

            // 发起请求
            result_array = SnsNetWork.MakeRequest(url, param, cookie, method, protocol);
            if (result_array.Ret != 0)
            {
                result_array.Ret += OPENAPI_ERROR_HTPP;
                return(result_array);
            }


            //解析返回结果的返回码
            string stat_ret = "";

            try
            {
                if (this.format == "xml")
                {
                    XmlDocument xml = new XmlDocument();
                    xml.LoadXml(result_array.Msg);
                    stat_ret = xml.LastChild["ret"].InnerText.ToString();
                }
                else
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    RstArray             json_obj   = new RstArray();
                    json_obj = serializer.Deserialize <RstArray>(result_array.Msg);
                    stat_ret = json_obj.Ret.ToString();
                }
            }
            catch (Exception e)
            {
                result_array.Msg = e.Message;
                // 远程返回的不是 json或者xml 格式, 说明返回包有问题
                result_array.Ret += OPENAPI_ERROR_RESPONSE_DATA_INVALID;
                return(result_array);
            }
            // 统计上报
            if (is_stat)
            {
                Dictionary <string, string> stat_params = new Dictionary <string, string>();
                stat_params["appid"]     = appid.ToString();
                stat_params["pf"]        = param["pf"];
                stat_params["rc"]        = stat_ret;
                stat_params["svr_name"]  = server_name;
                stat_params["interface"] = script_name;
                stat_params["protocol"]  = protocol;
                stat_params["method"]    = method;
                SnsStat.StatReport(stat_url, start_time, stat_params);
            }

            //通过调用以下方法,可以打印出调用openapi请求的返回码以及错误信息,不打印可以注释
            ///PrintRespond(result_array);

            return(result_array);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 执行一个 HTTP 请求
        /// </summary>
        /// <param name="url">执行请求的URL</param>
        /// <param name="param">表单参数</param>
        /// <param name="cookie">cookie参数 </param>
        /// <param name="method">请求方法 post / get</param>
        ///  <param name="protocol"> http协议类型 http / https</param>
        /// <returns>返回结果数组</returns>
        static public RstArray MakeRequest(string url, Dictionary <string, string> param, Dictionary <string, string> cookie, string method, string protocol)
        {
            string query_string  = MakeQueryString(param);
            string cookie_string = MakeCookieString(cookie);
            //结果
            RstArray result = new RstArray();
            //请求类
            HttpWebRequest request = null;
            //请求响应类
            HttpWebResponse response = null;
            //响应结果读取类
            StreamReader reader = null;

            //http连接数限制默认为2,多线程情况下可以增加该连接数,非多线程情况下可以注释掉此行代码
            ServicePointManager.DefaultConnectionLimit = 500;

            try
            {
                if (method.Equals("get", StringComparison.OrdinalIgnoreCase))
                {
                    if (url.IndexOf("?") > 0)
                    {
                        url = url + "&" + query_string;
                    }
                    else
                    {
                        url = url + "?" + query_string;
                    }
                    //如果是发送HTTPS请求
                    if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
                    {
                        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                        request = WebRequest.Create(url) as HttpWebRequest;
                        request.ProtocolVersion = HttpVersion.Version10;
                    }
                    else
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                    }
                    request.Method  = "GET";
                    request.Timeout = 3000;
                }
                else
                {
                    //如果是发送HTTPS请求
                    if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
                    {
                        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                        request = WebRequest.Create(url) as HttpWebRequest;
                        request.ProtocolVersion = HttpVersion.Version10;
                    }
                    else
                    {
                        request = WebRequest.Create(url) as HttpWebRequest;
                    }
                    //去掉“Expect: 100-Continue”请求头,不然会引起post(417) expectation failed
                    ServicePointManager.Expect100Continue = false;

                    request.Method      = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.Timeout     = 3000;
                    //POST数据
                    byte[] data = Encoding.UTF8.GetBytes(query_string);
                    using (Stream stream = request.GetRequestStream())
                    {
                        stream.Write(data, 0, data.Length);
                    }
                }

                //cookie
                if (cookie_string != null)
                {
                    request.Headers.Add("Cookie", cookie_string);
                }

                //response
                response = (HttpWebResponse)request.GetResponse();
                reader   = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

                //return
                result.Msg = reader.ReadToEnd();
                result.Ret = 0;
            }
            catch (Exception e)
            {
                result.Msg = e.Message;
                result.Ret = ERROR_SNSNETWORK_HTTP;
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
            return(result);
        }
Ejemplo n.º 3
0
 /// <summary>
 ///  打印出返回结果的内容,当API中的这个函数的注释放开将会被调用。
 /// </summary>
 /// <param name="RstArray">待打印的array</param>
 static private void PrintRespond(RstArray result_array)
 {
     HttpContext.Current.Response.Write("<br>============= respond info ================<br>");
     HttpContext.Current.Response.Write("ret = " + result_array.Ret + "<br>msg = " + result_array.Msg + "<br>");
 }
Ejemplo n.º 4
0
        /// <summary>
        /// 执行一个 HTTP 请求,以post方式,multipart/form-data的编码类型上传文件
        /// </summary>
        /// <param name="url">执行请求的URL</param>
        /// <param name="param">表单参数</param>
        /// <param name="cookie">cookie参数 </param>
        /// <param name="protocol"> http协议类型 http / https</param>
        ///  <param name="file_name"> 文件名,文件相应参数的参数名,例如/v3/t/add_pic_t中的 "pic" </param>
        ///  <param name="file_path"> 文件的路径 </param>
        /// <returns>返回结果数组</returns>
        public static RstArray MutilpartPostFile(string url, Dictionary <string, string> param, Dictionary <string, string> cookie,
                                                 string protocol, string file_name, string file_path)
        {
            //结果
            RstArray result = new RstArray();
            //请求类
            HttpWebRequest request = null;
            //包体填充类
            MemoryStream mem_stream = null;
            Stream       req_stream = null;

            //请求响应类
            HttpWebResponse response = null;
            //文件流
            FileStream file_stream = null;
            //响应结果读取类
            StreamReader reader = null;

            //http连接数限制默认为2,多线程情况下可以增加该连接数,非多线程情况下可以注释掉此行代码
            ServicePointManager.DefaultConnectionLimit = 500;

            try
            {
                //https请求
                if (protocol.Equals("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                    request = WebRequest.Create(url) as HttpWebRequest;
                    request.ProtocolVersion = HttpVersion.Version10;
                }
                else
                {
                    request = WebRequest.Create(url) as HttpWebRequest;
                }

                // 设置属性
                request.Method  = "POST";
                request.Timeout = 3000;

                //cookie
                string cookie_string = MakeCookieString(cookie);
                if (cookie_string != null)
                {
                    request.Headers.Add("Cookie", cookie_string);
                }

                //去掉“Expect: 100-Continue”请求头,不然会引起post(417) expectation failed
                ServicePointManager.Expect100Continue = false;

                //设置请求体
                mem_stream = new MemoryStream();

                //边界符
                string boundary       = "---------------" + DateTime.Now.Ticks.ToString("x");
                byte[] begin_boundary = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
                byte[] end_boundary   = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");

                request.ContentType = "multipart/form-data; boundary=" + boundary;

                //开头
                mem_stream.Write(begin_boundary, 0, begin_boundary.Length);

                //参数
                string param_format = "Content-Disposition: form-data; name=\"{0}\"" +
                                      "\r\n\r\n{1}\r\n--" + boundary + "\r\n";
                StringBuilder param_string = new StringBuilder();
                foreach (string key in param.Keys)
                {
                    param_string.AppendFormat(param_format, key, param[key]);
                }
                byte[] param_byte = Encoding.UTF8.GetBytes(param_string.ToString());
                mem_stream.Write(param_byte, 0, param_byte.Length);

                //文件
                file_stream = new FileStream(file_path, FileMode.Open, FileAccess.Read);
                string file_format = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                                     "Content-Type: application/octet-stream\r\n\r\n";
                string file_string = string.Format(file_format, file_name, file_path);
                byte[] file_byte   = Encoding.UTF8.GetBytes(file_string);
                mem_stream.Write(file_byte, 0, file_byte.Length);

                byte[] buffer = new byte[1024];
                int    bytes;
                while ((bytes = file_stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    mem_stream.Write(buffer, 0, bytes);
                }

                //结尾
                mem_stream.Write(end_boundary, 0, end_boundary.Length);


                request.ContentLength = mem_stream.Length;
                req_stream            = request.GetRequestStream();
                mem_stream.Position   = 0;
                byte[] temp_buffer = new byte[mem_stream.Length];
                mem_stream.Read(temp_buffer, 0, temp_buffer.Length);
                req_stream.Write(temp_buffer, 0, temp_buffer.Length);

                //响应
                response = (HttpWebResponse)request.GetResponse();
                reader   = new StreamReader(response.GetResponseStream(), Encoding.UTF8);

                //return
                result.Msg = reader.ReadToEnd();
                result.Ret = 0;
            }
            catch (Exception e)
            {
                result.Msg = e.Message;
                result.Ret = ERROR_SNSNETWORK_HTTP;
            }
            finally
            {
                if (request != null)
                {
                    request.Abort();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (file_stream != null)
                {
                    file_stream.Close();
                    file_stream.Dispose();
                }
                if (mem_stream != null)
                {
                    mem_stream.Close();
                    mem_stream.Dispose();
                }
                if (req_stream != null)
                {
                    req_stream.Close();
                    req_stream.Dispose();
                }
            }

            return(result);
        }