• Get HttpWebResponse and HttpClient Return String by proxy


            #region Get HttpClient Return String
            /// <summary>
            /// Get HttpClient Return String
            /// </summary>
            /// <param name="apiUrl">api Url</param>
            /// <returns></returns>
            static public string GetHttpClientReturnString(string apiUrl, string reqParams)
            {
                string result = string.Empty;
                try
                {
                    NetworkCredential proxyCredential = new NetworkCredential();
                    proxyCredential.UserName = proxyUserName;
                    proxyCredential.Password = proxyPassword;
    
                    WebProxy proxy = new WebProxy(proxyIpAddress);
                    proxy.Credentials = proxyCredential;
    
                    var httpClientHandler = new HttpClientHandler()
                    {
                        Proxy = proxy,
                    };
                    httpClientHandler.PreAuthenticate = true;
                    httpClientHandler.UseDefaultCredentials = false;
                    httpClientHandler.Credentials = proxyCredential;
                    var client = new HttpClient(handler: httpClientHandler, disposeHandler: true);
    
                    HttpContent content = new StringContent(reqParams);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
    
                    var responseString = client.GetStringAsync(apiUrl);
                    result = responseString.Result;
                }
                catch (Exception ex)
                {
                    result = ex.Message;
                }
                return result;
            }
            #endregion
    
            #region Get HttpWebResponse Return String
            /// <summary>
            /// Get HttpWebResponse Return String
            /// </summary>
            /// <param name="apiUrl">api Url</param>
            /// <param name="parameters">传递参数键值对</param>
            /// <param name="contentType">内容类型默认application/x-www-form-urlencoded</param>
            /// <param name="methord">请求方式默认POST</param>
            /// <param name="timeout">超时时间默认300000</param>
            /// <returns>响应字符串</returns>
            static public string GetHttpWebResponseReturnString(string apiUrl, Dictionary<string, object> parameters, string contentType = "application/x-www-form-urlencoded", string methord = "POST", int timeout = 300000)
            {
                string result = string.Empty;
                string responseText = string.Empty;
                try
                {
                    if (string.IsNullOrEmpty(apiUrl))
                    {
                        return "apiURl is null";
                    }
    
                    StringBuilder postData = new StringBuilder();
                    if (parameters != null && parameters.Count > 0)
                    {
                        foreach (var p in parameters)
                        {
                            if (postData.Length == 0)
                            {
                                postData.AppendFormat("{0}={1}", p.Key, p.Value);
                            }
                            else
                            {
                                postData.AppendFormat("&{0}={1}", p.Key, p.Value);
                            }
                        }
                    }
    
                    ServicePointManager.DefaultConnectionLimit = int.MaxValue;
    
                    NetworkCredential proxyCredential = new NetworkCredential();
                    proxyCredential.UserName = proxyUserName;
                    proxyCredential.Password = proxyPassword;
    
                    WebProxy proxy = new WebProxy(proxyIpAddress);
                    proxy.Credentials = proxyCredential;
    
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(apiUrl);
                    myRequest.Credentials = proxyCredential;
                    myRequest.Proxy = proxy;
    
                    myRequest.Timeout = timeout;
                    myRequest.ServicePoint.MaxIdleTime = 1000;
                    if (!string.IsNullOrEmpty(contentType))
                    {
                        myRequest.ContentType = contentType;
                    }
                    myRequest.ServicePoint.Expect100Continue = false;
                    myRequest.Method = methord;
                    byte[] postByte = Encoding.UTF8.GetBytes(postData.ToString());
                    myRequest.ContentLength = postData.Length;
    
                    using (Stream writer = myRequest.GetRequestStream())
                    {
                        writer.Write(postByte, 0, postData.Length);
                    }
    
                    using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8))
                        {
                            responseText = reader.ReadToEnd();
                        }
                    }
                    if (!string.IsNullOrEmpty(responseText))
                    {
                        result = responseText;
                    }
                    else
                    {
                        result = "The remote service is not responding. Please try again later.";
                    }
                }
                catch (Exception ex)
                {
                    result = string.Format("Request exception:{0}, please try again later.", ex.Message);
                }
                return result;
            }
    
            #endregion
    View Code
            #region Other
    
            /// <summary>
            /// WebRequest请求方法
            /// </summary>
            /// <param name="url"></param>
            /// <param name="strJson"></param>
            /// <returns></returns>
            static public string HttpClientPost(string url, string strJson)
            {
                try
                {
                    string responseStr = string.Empty;
    
                    WebRequest request = WebRequest.Create(url);
                    request.Method = "Post";
                    request.ContentType = "application/json";
    
                    byte[] requestData = System.Text.Encoding.UTF8.GetBytes(strJson);
                    request.ContentLength = requestData.Length;
    
                    Stream newStream = request.GetRequestStream();
                    newStream.Write(requestData, 0, requestData.Length);
                    newStream.Close();
    
                    var response = request.GetResponse();
                    Stream ReceiveStream = response.GetResponseStream();
                    using (StreamReader stream = new StreamReader(ReceiveStream, Encoding.UTF8))
                    {
                        responseStr = stream.ReadToEnd();
                    }
    
                    return responseStr;
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
            }
    
            /// <summary>
            /// post异步请求方法
            /// </summary>
            /// <param name="url"></param>
            /// <param name="strJson"></param>
            /// <returns></returns>
            static public async Task<string> PostAsync(string url, string strJson)
            {
                try
                {
                    HttpContent content = new StringContent(strJson);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    HttpClient client = new HttpClient();
                    HttpResponseMessage res = await client.PostAsync(url, content);
                    if (res.StatusCode == HttpStatusCode.OK)
                    {
                        string str = res.Content.ReadAsStringAsync().Result;
                        return str;
                    }
                    else
                        return null;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
    
            /// <summary>
            /// post同步请求方法
            /// </summary>
            /// <param name="url"></param>
            /// <param name="strJson"></param>
            /// <returns></returns>
            static public string Post(string url, string strJson)
            {
                try
                {
                    HttpContent content = new StringContent(strJson);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    //client.DefaultRequestHeaders.Connection.Add("keep-alive");
                    HttpClient client = new HttpClient();
                    Task<HttpResponseMessage> res = client.PostAsync(url, content);
                    if (res.Result.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        string str = res.Result.Content.ReadAsStringAsync().Result;
                        return str;
                    }
                    else
                        return null;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
    
            static public string HttpClientGet(string url)
            {
                try
                {
                    HttpClient client = new HttpClient();
                    var responseString = client.GetStringAsync(url);
                    return responseString.Result;
                }
                catch (Exception ex)
                {
                    return null;
                }
            }
    
            #endregion
    View Code
  • 相关阅读:
    简单 || 复杂
    命令行参数 && json 协议 && 自定义 error 类型
    Circos安装 (转+总结)
    ggplot2—Pathway富集分析气泡图
    ggplot2绘图
    linux常用命令小结
    生信学习网站
    Perl学习建议(转)
    R作图函数(转)
    Android viewPager+fragment实现滑页效果
  • 原文地址:https://www.cnblogs.com/hofmann/p/11307932.html
Copyright © 2020-2023  润新知