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 = )
{
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的更多相关文章
- 获取验证码随机字符串@return string $captcha,随机验证码文字
<?php//验证码工具类class Captcha{//属性private $width;private $height;private $fontsize;private $pixes;pr ...
- HttpWebRequest、HttpWebResponse、HttpClient、WebClient等http网络访问类的使用示例汇总
工作中长期需要用到通过HTTP调用API以及文件上传下载,积累了不少经验,现在将各种不同方式进行一个汇总. 首先是HttpWebRequest: /// <summary> /// 向服务 ...
- .NET WCF Return String 字符串有反斜杠的处理
应该是: {"Message":"Hello World"} 结果是:" {\"Message\":\"Hello Wo ...
- C#向远程地址发送数据
static string proxyIpAddress = AppConfig.GetProxyIpAddress; static string proxyUserName = AppConfig. ...
- 用java实现新浪爬虫,代码完整剖析(仅针对当前SinaSignOn有效)
先来看我们的web.xml文件,如下 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application ...
- HttpClient(4.3.5) - HttpClient Proxy Configuration
Even though HttpClient is aware of complex routing scemes and proxy chaining, it supports only simpl ...
- httpclient设置proxy与proxyselector
If single proxy for all targets is enough for you: HttpComponentsClientHttpRequestFactory clientHttp ...
- WebApi 异步请求(HttpClient)
还是那几句话: 学无止境,精益求精 十年河东,十年河西,莫欺少年穷 学历代表你的过去,能力代表你的现在,学习代表你的将来 废话不多说,直接进入正题: 今天公司总部要求各个分公司把短信接口对接上,所谓的 ...
- 关于 C# HttpClient的 请求
Efficiently Streaming Large HTTP Responses With HttpClient Downloading large files with HttpClient a ...
随机推荐
- Raspberry Pi 摄像头模块入门
目录 一.摄像头模块安装 二.使用命令控制摄像头 三.使用Python程序控制摄像头 四.基于vlc的Raspberry Pi摄像头实时监控 参考资料 Raspberry Pi提供了摄像头模块的接口, ...
- ArcGIS Server“无法创建站点,计算机不具有有效的的许可”
问题描述 ArcGIS Server10.5安装过程中,所有授权和破解均已完成,但是最后一步创建站点的时候显示创建失败,会出现如下图所示的问题:既“无法创建站点,计算机不具有有效的的许可…”,经历了卸 ...
- mysql之group_concat函数
mysql之group_concat函数 在介绍GROUP_CONCAT之前,我们先来看看concat()函数和concat_ws()函数. 先准备一个测试数据库: mysql> select ...
- Oracle JDBC 标准连接实例
Oracle JDBC 标准连接实例 // 创建一个数据库连接 Connection con = null; // 创建预编译语句对象,一般用PreparedStatement不用Statement ...
- linux 下 tcpdump 命令详解
用途 在网络上转储流量 语法 tcpdump [ -a ] [ -A ] [ -B buffer_size ] [ -d ] [ -D ] [ -e ] [ -f ] [ -l ] [ -K ] [ ...
- CSS — 隐藏滚动条,依旧可以滚动
公司的系统,在PC端可以管理我们的公众号,在发布模块页面时有一个预览功能,呈现页面在手机端的样式. 做法很简单,一会就完成了,但是在预览内容过长时手机外框会有一个滚动条,影响美观,于是就想把它去掉,有 ...
- based on Greenlets (via Eventlet and Gevent) fork 孙子worker 比较
Design — Gunicorn 19.9.0 documentationhttp://docs.gunicorn.org/en/stable/design.html#async-workers e ...
- 【I·M·U_Ops】------Ⅰ------ IMU自动化运维平台设想
说明本脚本仅作为学习使用,请勿用于任何商业用途.本文为原创,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接和本声明. #A 搞这个平台的初心 由于之前呆的单位所有IT相关硬件资源都要我们 ...
- Linux Mint设置自定义快捷键
我使用的是 Linux Mint 19.2 Tina 先搜索键盘,把键盘的功能调出来 快捷键--->>自定义快捷键--->>添加自定义快捷键 名称可自定义(这里我定义的是“截图 ...
- idea控制台中文乱码“淇℃伅”
方法一:找到tomcat的conf目录下的logging.properties,将输出到控制台的编码改为GBK java.util.logging.ConsoleHandler.encoding = ...