Exemplo n.º 1
0
            public virtual int ExecuteMethod(PostMethod method)
            {
                var request = (HttpWebRequest)WebRequest.Create(method.Uri);

                request.Method        = "POST";
                request.ContentType   = method.MimeType;
                request.ContentLength = method.Content.Length;

                var requestStream = request.GetRequestStream();

                requestStream.Write(method.Content, 0, method.Content.Length);
                requestStream.Flush();
                requestStream.Close();

                try
                {
                    method.Response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    //.NET throws if the server answers with a 500 status code
                    if (ex.Response != null)
                    {
                        method.Response = (HttpWebResponse)ex.Response;
                    }
                    else
                    {
                        throw;
                    }
                }

                return((int)method.Response.StatusCode);
            }
    private IEnumerator ConnectToGAS(PostMethod method, Action <string> onComplete = null, List <FieldData> fieldData = null)
    {
        WWWForm form = new WWWForm();

        form.AddField("method", method.ToString());

        if (fieldData != null)
        {
            foreach (FieldData f in fieldData)
            {
                form.AddField(f.FieldName, f.FieldValue);
            }
        }

        using (UnityWebRequest www = UnityWebRequest.Post(GAS_URL, form))
        {
            yield return(www.SendWebRequest());

            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                var outputMsg = www.downloadHandler.text;
                onComplete?.Invoke(outputMsg);

                Debug.LogFormat("Method : {0}, Message : {1}", method.ToString(), outputMsg);
            }
        }
    }
Exemplo n.º 3
0
        /// <summary>
        /// 向需要AccessToken的API发送消息的公共方法
        /// </summary>
        /// <param name="accessToken">这里的AccessToken是通用接口的AccessToken,非OAuth的。如果不需要,可以为null,此时urlFormat不要提供{0}参数</param>
        /// <param name="urlFormat"></param>
        /// <param name="data">如果是Get方式,可以为null</param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <returns></returns>
        public static T Send <T>(string accessToken, string urlFormat, object data, CommonJsonSendType sendType = CommonJsonSendType.POST, int timeOut = Config.TIME_OUT) where T : WxJsonResult, new()
        {
            var url = string.IsNullOrEmpty(accessToken) ? urlFormat : string.Format(urlFormat, accessToken);

            switch (sendType)
            {
            case CommonJsonSendType.GET:
                return(GetMethod.GetJson <T>(url));

            case CommonJsonSendType.POST:
                SerializerHelper serializerHelper = new SerializerHelper();
                var jsonString = serializerHelper.GetJsonString(data);
                using (MemoryStream ms = new MemoryStream())
                {
                    var bytes = Encoding.UTF8.GetBytes(jsonString);
                    ms.Write(bytes, 0, bytes.Length);
                    ms.Seek(0, SeekOrigin.Begin);

                    return(PostMethod.PostGetJson <T>(url, null, ms, timeOut: timeOut));
                }

            default:
                throw new ArgumentOutOfRangeException("sendType");
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// 上传客服头像
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="kfAccount">完整客服账号,格式为:账号前缀@公众号微信号</param>
        /// <param name="file">form-data中媒体文件标识,有filename、filelength、content-type等信息</param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <returns></returns>
        public static WxJsonResult UploadCustomHeadimg(string accessToken, string kfAccount, string file, int timeOut = Config.TIME_OUT)
        {
            var url            = string.Format("http://api.weixin.qq.com/customservice/kfaccount/uploadheadimg?access_token={0}&kf_account={1}", accessToken, kfAccount);
            var fileDictionary = new Dictionary <string, string>();

            fileDictionary["media"] = file;
            return(PostMethod.PostFileGetJson <WxJsonResult>(url, null, fileDictionary, null, timeOut: timeOut));
        }
Exemplo n.º 5
0
        /// <summary>
        /// 新增临时素材(原上传媒体文件)
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="type"></param>
        /// <param name="file"></param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <returns></returns>
        public static UploadTemporaryMediaResult UploadTemporaryMedia(string accessToken, UploadMediaFileType type, string file, int timeOut = Config.TIME_OUT)
        {
            var url            = string.Format("http://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", accessToken, type.ToString());
            var fileDictionary = new Dictionary <string, string>();

            fileDictionary["media"] = file;
            return(PostMethod.PostFileGetJson <UploadTemporaryMediaResult>(url, null, fileDictionary, null, timeOut: timeOut));
        }
Exemplo n.º 6
0
        /// <summary>
        /// 上传图片素材
        /// 上传在摇一摇页面展示的图片素材,素材保存在微信侧服务器上。 格式限定为:jpg,jpeg,png,gif,图片大小建议120px*120 px,限制不超过200 px *200 px,图片需为正方形。
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="file"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static UploadImageResultJson UploadImage(string accessToken, string file, int timeOut = Config.TIME_OUT)
        {
            var url            = string.Format("https://api.weixin.qq.com/shakearound/material/add?access_token={0}", accessToken);
            var fileDictionary = new Dictionary <string, string>();

            fileDictionary["media"] = file;
            return(PostMethod.PostFileGetJson <UploadImageResultJson>(url, null, fileDictionary, null, timeOut: timeOut));
        }
Exemplo n.º 7
0
        /// <summary>
        /// 新增永久视频素材
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="file">文件路径</param>
        /// <param name="title"></param>
        /// <param name="introduction"></param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <returns></returns>
        public static UploadForeverMediaResult UploadForeverVideo(string accessToken, string file, string title, string introduction, int timeOut = Config.TIME_OUT)
        {
            var url            = string.Format("http://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}", accessToken);
            var fileDictionary = new Dictionary <string, string>();

            fileDictionary["media"]       = file;
            fileDictionary["description"] = string.Format("{{\"title\":\"{0}\", \"introduction\":\"{1}\"}}", title, introduction);

            return(PostMethod.PostFileGetJson <UploadForeverMediaResult>(url, null, fileDictionary, null, timeOut: timeOut));
        }
Exemplo n.º 8
0
        protected virtual PostMethod CreatePostMethod()
        {
            var method = new PostMethod(url)
            {
                MimeType = MimeTypes.XML, Charset = "UTF-8"
            };

            method.MimeType = MimeTypes.XML;
            method.Charset  = "UTF-8";

            return(new PostMethod(url));
        }
Exemplo n.º 9
0
        private GetMemberResult GetMemberFunc(int weixinId, string openId)
        {
            var url      = _passport.ApiUrl + "GetMember";
            var formData = new Dictionary <string, string>();

            formData["token"]    = _passport.Token;
            formData["openid"]   = openId;
            formData["weixinId"] = weixinId.ToString();

            var result = PostMethod.PostGetJson <GetMemberResult>(url, formData: formData);

            return(result);
        }
Exemplo n.º 10
0
        private string PostMethod(PostMethod method)
        {
            int statusCode = client.ExecuteMethod(method);

            if (IsOk(statusCode))
            {
                return(UnwrapFromSoap(method));
            }

            log.Warn("Status code " + statusCode);

            throw new HttpTransportLayerException(statusCode);
        }
Exemplo n.º 11
0
        /// <summary>
        /// 获取永久素材(除了图文)
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="mediaId"></param>
        /// <param name="stream"></param>
        public static void GetForeverMedia(string accessToken, string mediaId, Stream stream)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}",
                                    accessToken);
            var data = new
            {
                media_id = mediaId
            };
            SerializerHelper serializerHelper = new SerializerHelper();
            var jsonString = serializerHelper.GetJsonString(data);

            PostMethod.Download(url, jsonString, stream);
        }
Exemplo n.º 12
0
        /// <summary>
        /// 新增其他类型永久素材(图片(image)、语音(voice)和缩略图(thumb))
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="file">文件路径</param>
        /// <param name="timeOut">代理请求超时时间(毫秒)</param>
        /// <returns></returns>
        public static UploadForeverMediaResult UploadForeverMedia(string accessToken, string file, int timeOut = Config.TIME_OUT)
        {
            var url = string.Format("http://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}", accessToken);

            //因为有文件上传,所以忽略dataDictionary,全部改用文件上传格式
            //var dataDictionary = new Dictionary<string, string>();
            //dataDictionary["type"] = UploadMediaFileType.image.ToString();

            var fileDictionary = new Dictionary <string, string>();

            //fileDictionary["type"] = UploadMediaFileType.image.ToString();//不提供此参数也可以上传成功
            fileDictionary["media"] = file;
            return(PostMethod.PostFileGetJson <UploadForeverMediaResult>(url, null, fileDictionary, null, timeOut: timeOut));
        }
Exemplo n.º 13
0
        internal virtual PostMethod CreatePostMethod(RequestMessage requestMessage)
        {
            var name = requestMessage.GetInteractionId();

            var service = ServiceDefinition.GetService(name);

            if (service == null)
            {
                throw new TransportLayerException("Cannot find a Mohawk service for type " + name);
            }

            var method = new PostMethod(Concatenate(url, service.GetPath()));

            byte[] soapEnvelope = WrapInSoapEnvelope(requestMessage.GetMessageAsDocument(), service);

            method.MimeType = "application/soap+xml";
            method.Content  = soapEnvelope;


            return(method);
        }
Exemplo n.º 14
0
            public virtual int ExecuteMethod(PostMethod method)
            {
                var request = (HttpWebRequest)WebRequest.Create(method.Uri);

                request.Method        = "POST";
                request.ContentType   = method.MimeType;
                request.ContentLength = method.Content.Length;

                if (!String.IsNullOrEmpty(method.UserName))
                {
                    request.Credentials = new NetworkCredential(method.UserName, String.IsNullOrEmpty(method.Password) ? String.Empty : method.Password);
                }

                var requestStream = request.GetRequestStream();

                requestStream.Write(method.Content, 0, method.Content.Length);
                requestStream.Flush();
                requestStream.Close();

                try
                {
                    method.Response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    //.NET throws if the server answers with a 500 status code
                    if (ex.Response != null)
                    {
                        method.Response = (HttpWebResponse)ex.Response;
                    }
                    else
                    {
                        throw;
                    }
                }

                return((int)method.Response.StatusCode);
            }
Exemplo n.º 15
0
        public static string GetPostDataWithCookie(string url, string postDataStr, PostMethod method, CookieContainer cookieContainer)
        {
            Encoding encoding = Encoding.GetEncoding("utf-8");

            byte[] data = encoding.GetBytes(postDataStr);
            //准备发送请求
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.CookieContainer = cookieContainer;
            webRequest.ContentType     = "application/x-www-form-urlencoded";
            webRequest.ContentLength   = data.Length;
            webRequest.Method          = method == PostMethod.Post ? "POST" : "GET";
            Stream webStream = webRequest.GetRequestStream();

            //发送数据
            webStream.Write(data, 0, data.Length);
            webStream.Close();
            //获取返回数据
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
            StreamReader    reader      = new StreamReader(webResponse.GetResponseStream(), Encoding.GetEncoding("utf-8"));
            var             retString   = reader.ReadToEnd();

            return(retString);
        }
Exemplo n.º 16
0
 public HttpWebResponse PostData(PostMethod method)
 {
     if (method == PostMethod.Multipart) return PostMultipart();
     else if (method == PostMethod.UrlEncoded) return PostUrlEncoded();
     else throw new ArgumentException();
 }
Exemplo n.º 17
0
        private static bool HandleCredentials(CredentialsProvider credentialProvider, PostMethod postMethod)
        {
            var credentials = (UsernamePasswordCredentials)credentialProvider.GetCredentials();

            if (credentials != null)
            {
                postMethod.UserName = credentials.GetUsername();
                postMethod.Password = credentials.GetPassword();
            }

            return(credentials != null);
        }
Exemplo n.º 18
0
        private static string UnwrapFromSoap(PostMethod method)
        {
            var sr = new StreamReader(method.Response.GetResponseStream(), Encoding.Default);

            return(new Hl7MessageExtractor().GetHl7Message(sr.BaseStream));
        }