#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 = )
{
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 > )
{
foreach (var p in parameters)
{
if (postData.Length == )
{
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 = ;
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, , 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
        #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, , 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

Get HttpWebResponse and HttpClient Return String by proxy的更多相关文章

  1. 获取验证码随机字符串@return string $captcha,随机验证码文字

    <?php//验证码工具类class Captcha{//属性private $width;private $height;private $fontsize;private $pixes;pr ...

  2. HttpWebRequest、HttpWebResponse、HttpClient、WebClient等http网络访问类的使用示例汇总

    工作中长期需要用到通过HTTP调用API以及文件上传下载,积累了不少经验,现在将各种不同方式进行一个汇总. 首先是HttpWebRequest: /// <summary> /// 向服务 ...

  3. .NET WCF Return String 字符串有反斜杠的处理

    应该是: {"Message":"Hello World"} 结果是:" {\"Message\":\"Hello Wo ...

  4. C#向远程地址发送数据

    static string proxyIpAddress = AppConfig.GetProxyIpAddress; static string proxyUserName = AppConfig. ...

  5. 用java实现新浪爬虫,代码完整剖析(仅针对当前SinaSignOn有效)

    先来看我们的web.xml文件,如下 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application ...

  6. HttpClient(4.3.5) - HttpClient Proxy Configuration

    Even though HttpClient is aware of complex routing scemes and proxy chaining, it supports only simpl ...

  7. httpclient设置proxy与proxyselector

    If single proxy for all targets is enough for you: HttpComponentsClientHttpRequestFactory clientHttp ...

  8. WebApi 异步请求(HttpClient)

    还是那几句话: 学无止境,精益求精 十年河东,十年河西,莫欺少年穷 学历代表你的过去,能力代表你的现在,学习代表你的将来 废话不多说,直接进入正题: 今天公司总部要求各个分公司把短信接口对接上,所谓的 ...

  9. 关于 C# HttpClient的 请求

    Efficiently Streaming Large HTTP Responses With HttpClient Downloading large files with HttpClient a ...

随机推荐

  1. Leetcode题目322.零钱兑换(动态规划-中等)

    题目描述: 给定不同面额的硬币 coins 和一个总金额 amount.编写一个函数来计算可以凑成总金额所需的最少的硬币个数.如果没有任何一种硬币组合能组成总金额,返回 -1. 示例 1: 输入: c ...

  2. (一)OpenCV-Python学习—基础知识

    opencv是一个强大的图像处理和计算机视觉库,实现了很多实用算法,值得学习和深究下. 1.opencv包安装 · 这里直接安装opencv-python包(非官方): pip install ope ...

  3. MyBatis——特殊传参问题小结

    近期在写系统报表API的时候遇到MyBatis中的一些特殊写法: 1. 传入两个参数(一般情况下我们更多的是传入一个对象或者map) public List<MarketVehicleModel ...

  4. nginx ssl

    SSL 私钥/etc/pki/CA/ (umask 077;openssl genrsa -out private/cakey.pem 2048) 自签证书 openssl req -new -x50 ...

  5. 阶段5 3.微服务项目【学成在线】_day02 CMS前端开发_04-vuejs研究-vuejs基础-v-model指令

    <!DOCTYPE html> <html lang="en" xmlns:v‐on="http://www.w3.org/1999/xhtml&quo ...

  6. [dart学习]第五篇:操作符

    前言:本系列内容假设读者有一定的编程基础,如了解C语言.python等. 本节一起来学习dart的操作符,直接拷贝官网的操作符描述表如下: Description Operator unary pos ...

  7. [C++]数据结构:线性表之(单)链表

    一 (单)链表 ADT + Status InitList(LinkList &L) 初始化(单)链表 + void printList(LinkList L) 遍历(单)链表 + int L ...

  8. lexicalized Parsing

    $q$(S $\rightarrow$ NP VP) * $q$(NP $\rightarrow$ NNP) * $q$(VP $\rightarrow$ VB NP) * $q$(NP $\righ ...

  9. 文件夹中含有子文件夹,修改子文件夹中的图像存储格式(python实现)

    文件夹中含有子文件夹,修改子文件夹中的图像存储格式,把png图像改为jpg图像,python代码如下: import os import cv2 filePath = 'C:\\Users\\admi ...

  10. JDK1.8新特性之Optional

    概念 Optional 是JDK1.8中出现的一个容器类,代表一个值存在或者不存在.原来使用null表示一个值不存在,现在Optional可以更好的表达这个概念.并且可以避免空指针异常. 场景分析 需 ...