/// <summary>
        /// http get 请求
        /// </summary>
        /// <param name="url">url 地址</param>
        /// <param name="isKeepAlive">是否保持长连接</param>
        /// <returns>ResponseContent</returns>
        public static async Task <ResponseContent> GetAsync(string url, Boolean isKeepAlive = false)
        {
            try
            {
                if (isKeepAlive == true)
                {
                    if (!mHttpClient.DefaultRequestHeaders.Connection.Contains(keepAlive))
                    {
                        mHttpClient.DefaultRequestHeaders.Connection.Add(keepAlive);
                    }
                }
                else
                {
                    mHttpClient.DefaultRequestHeaders.Connection.Remove(keepAlive);
                }
                string obj = await mHttpClient.GetAsync(url).Result.Content.ReadAsStringAsync();

                ConsoleHelper.writeLine(obj);
                return((ResponseContent)JsonHelper.JsonToObject(obj, typeof(ResponseContent)));
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        ///  Get http请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns>响应流字符串</returns>
        public static ResponseContent Get(string url)
        {
            ResponseContent responseContent = new ResponseContent();

            if (getLocalConnectionStatus() <= 0)
            {
                responseContent.Code = -1;
                responseContent.Msg  = "网络未连接";
                responseContent.Data = "";
                return(responseContent);
            }
            if (!string.IsNullOrEmpty(url))
            {
                Stream          responseStream = null;
                StreamReader    streamReader   = null;
                HttpWebResponse webResponse    = null;
                try
                {
                    String res = GetRespStr(url, responseStream, streamReader, webResponse);
                    responseContent = (ResponseContent)JsonHelper.JsonToObject(res, typeof(ResponseContent));
                }
                catch (Exception ex)
                {
                    ConsoleHelper.writeLine(ex.Message + "location: HttpWebRequestHelper Get");
                    responseContent.Code = -1;
                    responseContent.Msg  = "请求失败:客户端口或者服务有误。";
                    responseContent.Data = "";
                    if (ex is WebException)
                    {
                        responseContent.Msg = "请求失败:" + ex.Message;
                    }
                }
                finally
                {
                    if (responseStream != null)
                    {
                        responseStream.Dispose();
                    }
                    if (streamReader != null)
                    {
                        streamReader.Dispose();
                    }
                    if (webResponse != null)
                    {
                        webResponse.Dispose();
                    }
                }
            }
            else
            {
                responseContent.Code = -1;
                responseContent.Msg  = "请求地址错误!";
                responseContent.Data = "";
            }
            return(responseContent);
        }
示例#3
0
        /// <summary>
        /// 汉字转化为拼音
        /// </summary>
        /// <param name="str">汉字</param>
        /// <param name="returnType">返回的类型,1大写 2 小写 3首字符大字</param>
        ///  <param name="isHasSpace">是否用空格分开,默认True</param>
        /// <returns>全拼</returns>
        public static string GetAllSpell(string text, int returnType = 3, Boolean isHasSpace = true)
        {
            string temp = String.Empty;

            foreach (Char obj in text)
            {
                try
                {
                    ChineseChar cc = new ChineseChar(obj);
                    string      c  = cc.Pinyins[0].ToString();
                    ConsoleHelper.writeLine(c);
                    switch (returnType)
                    {
                    case 1:
                        if (isHasSpace == false)
                        {
                            temp += c.Substring(0, c.Length - 1);
                        }
                        else
                        {
                            temp += c.Substring(0, c.Length - 1) + " ";
                        }
                        break;

                    case 2:
                        if (isHasSpace == false)
                        {
                            temp += c.Substring(0, c.Length - 1).ToLower();
                        }
                        else
                        {
                            temp += c.Substring(0, c.Length - 1).ToLower() + " ";
                        }
                        break;

                    case 3:
                        if (isHasSpace == false)
                        {
                            temp += (c.Substring(0, 1) + c.Substring(1, c.Length - 2).ToLower());
                        }
                        else
                        {
                            temp += (c.Substring(0, 1) + c.Substring(1, c.Length - 2).ToLower()) + " ";
                        }
                        break;
                    }
                }
                catch
                {
                    temp += obj.ToString();
                }
            }
            return(temp);
        }
        public static async Task <ResponseContent> PostFile(string url, string filePath, string postData = null)
        {
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(filePath))
            {
                throw new Exception("request url or  filePath is null !");
            }
            if (!FileHelper.Exists(filePath))
            {
                throw new Exception("file not exists 文件不存在!");
            }

            // 读文件流
            FileStream fileStream = null;

            try
            {
                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            }
            catch (Exception e)
            {
                ConsoleHelper.writeLine(e.Message);
                throw;
            }
            finally
            {
                fileStream.Close();
            }
            //设置请求头
            // fileHttpClient.DefaultRequestHeaders.Add("user-agent", "User-Agent    Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; MALNJS; rv:11.0) like Gecko");
            //为文件流提供的HTTP容器
            HttpContent fileContent = new StreamContent(fileStream);

            //设置媒体类型
            fileContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("multipart/form-data");
            //创建用于可传递文件的容器
            MultipartFormDataContent dataContent = new MultipartFormDataContent();
            string fileName = filePath.Substring(filePath.LastIndexOf("/") + 1);

            dataContent.Add(fileContent, "form", fileName);
            HttpResponseMessage resMessage = await fileHttpClient.PostAsync(url, dataContent);

            resMessage.EnsureSuccessStatusCode();
            string result = await resMessage.Content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(result))
            {
                return(null);
            }
            return(JsonHelper.JsonToObject(result, typeof(ResponseContent)) as ResponseContent);
        }
        public static ResponseContent downloadFile(String url, String savePath)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                request.AllowAutoRedirect = true;
                request.Method            = "Get";
                request.CookieContainer   = mCookieContainer;
                HttpWebResponse response   = (HttpWebResponse)request.GetResponse();
                long            totalBytes = response.ContentLength;
                Stream          rs         = response.GetResponseStream();
                Stream          fs         = new FileStream(savePath, FileMode.Create);
                StreamReader    reader     = new  StreamReader(rs);
                string          resStr     = reader.ReadToEnd();

                ResponseContent content = JsonHelper.JsonToObject <ResponseContent>(resStr);

                if (content == null)
                {
                    long   totalDownloadedByte = 0;
                    byte[] by    = new byte[1024];
                    int    osize = rs.Read(by, 0, by.Length);
                    while (osize > 0)
                    {
                        totalDownloadedByte = osize + totalDownloadedByte;
                        fs.Write(by, 0, osize);
                        osize = rs.Read(by, 0, (int)by.Length);
                    }
                    rs.Close();
                    fs.Close();

                    return(new ResponseContent()
                    {
                        Code = 0, Msg = "下载成功", Data = savePath
                    });
                }
                else
                {
                    return(content);
                }
            }
            catch (Exception e) {
                ConsoleHelper.writeLine(e.Message);
                return(new ResponseContent()
                {
                    Code = -1, Msg = e.Message, Data = ""
                });
            }
        }
        /// <summary>
        /// Post Http请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="postData">传输数据  "table=company&data=00"</param>
        /// <returns>泛型集合</returns>
        public static ResponseContent Post(string url, string postData, bool withCookes = true)
        {
            ResponseContent responseContent = new ResponseContent();

            if (getLocalConnectionStatus() <= 0)
            {
                responseContent.Code = -1;
                responseContent.Msg  = "网络未连接";
                responseContent.Data = "";
                return(responseContent);
            }

            if (string.IsNullOrEmpty(url))
            {
                responseContent.Code = -1;
                responseContent.Msg  = "请求的地址不能为空";
                responseContent.Data = "";
                return(responseContent);
            }
            HttpWebResponse webResponse    = null;
            Stream          responseStream = null;
            Stream          requestStream  = null;
            StreamReader    streamReader   = null;

            try
            {
                string respstr = PostStreamReader(url, responseStream, requestStream, streamReader, webResponse, postData, contentType);
                ConsoleHelper.writeLine(respstr);
                responseContent = JsonHelper.JsonToObject <ResponseContent>(respstr);
            }
            catch (Exception e)
            {
                ConsoleHelper.writeLine(" 请求失败: " + e.Message);
                responseContent.Code = -1;
                responseContent.Msg  = "请求失败:客户端口或者服务有误。";
                responseContent.Data = "";
                if (e is WebException)
                {
                    responseContent.Msg = e.Message;
                }
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Dispose();
                }
                if (webResponse != null)
                {
                    webResponse.Dispose();
                }
                if (requestStream != null)
                {
                    requestStream.Dispose();
                }
                if (streamReader != null)
                {
                    streamReader.Dispose();
                }
            }
            return(responseContent);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="filePath">路径</param>
        /// <param name="postData">参数</param>
        /// <param name="contentType">媒体类型</param>
        /// <param name="encode">编码</param>
        /// <returns></returns>
        public static ResponseContent postFile(string url, string filePath, string postData = null, string contentType = "application/octet-stream", string encode = "UTF-8")
        {
            if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(filePath))
            {
                throw new Exception("request url or  filePath is null !");
            }
            if (!FileHelper.Exists(filePath))
            {
                throw new Exception("file not exists 文件不存在!");
            }
            Stream          requestStream  = null;
            Stream          responseStream = null;
            StreamReader    streamReader   = null;
            FileStream      fileStream     = null;
            ResponseContent response       = new ResponseContent();

            try
            {
                // 设置参数
                HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
                //SetAuth(webRequest);
                webRequest.AllowAutoRedirect = true;
                webRequest.Method            = "POST";
                webRequest.CookieContainer   = mCookieContainer;
                string boundary = DateTime.Now.Ticks.ToString("X");                                // 随机分隔线
                webRequest.ContentType = "multipart/form-data;charset=" + encode + ";boundary=" + boundary;
                byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");   //消息开始
                byte[] endBoundaryBytes  = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); //消息结尾
                var    fileName          = filePath.Substring(filePath.LastIndexOf("/") + 1);
                //请求头部信息
                string postHeader      = string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:{1}\r\n\r\n", fileName, contentType);
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
                fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                byte[] fileByteArr = new byte[fileStream.Length];
                fileStream.Read(fileByteArr, 0, fileByteArr.Length);
                fileStream.Close();
                requestStream = webRequest.GetRequestStream();
                requestStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
                requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                requestStream.Write(fileByteArr, 0, fileByteArr.Length);
                if (!string.IsNullOrEmpty(postData))
                {
                    byte[] data = Encoding.UTF8.GetBytes(postData);
                    requestStream.Write(data, 0, data.Length);
                }
                requestStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                requestStream.Close();
                //发送请求,得到响应流
                responseStream = webRequest.GetResponse().GetResponseStream();
                if (responseStream == null)
                {
                    response.Data = string.Empty;
                    response.Msg  = "no respose 没有返回!";
                    response.Code = -1;
                }
                streamReader = new StreamReader(responseStream, Encoding.UTF8);
                response     = JsonHelper.JsonToObject <ResponseContent>(streamReader.ReadToEnd());
                return(response);
            }
            catch (Exception ex)
            {
                ConsoleHelper.writeLine("请求错误:" + ex.Message);
                return(null);
            }
            finally
            {
                if (requestStream != null)
                {
                    requestStream.Close();
                }
                if (responseStream != null)
                {
                    responseStream.Close();
                }
                if (streamReader != null)
                {
                    streamReader.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }