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 ...
随机推荐
- 重读APUE(1)-lseek注意事项
lseek使用的注意事项: 1. lseek的返回值,成功返回新的文件偏移量,失败返回-1,不能用<0判断:因为文件偏移量可能是正的,也可能是负的,所以不能使用<0判断成功与否:注意:对于 ...
- cookie和session的区别及其原理
1.为什么要有cookie/session? HTTP是一种无状态的协议,为了分辨链接是谁发起的,需自己去解决这个问题.不然有些情况下即使是同一个网站每打开一个页面也都要登录一下.而Session和C ...
- jenkin自动化代码上线
介绍 Jenkins是一款开源自动化服务器,旨在自动化连续集成和交付软件所涉及的重复技术任务. Jenkins是基于Java的,可以从Ubuntu软件包安装,也可以通过下载和运行其Web应用程序ARc ...
- [Java复习] Spring Boot
什么是Spring Boot? 传统SSH/SSM框架配置繁琐,有很多重复的模板配置,效率不高. Spring Boot快速创建可独立运行,生产级别的Spring应用程序. 主要是基于Spring家族 ...
- osg ifc ifccolumn
- 免费的HTML5版uploadify
转http://www.cnblogs.com/lvdabao/p/3452858.html var defaults = { fileTypeExts:'',//允许上传的文件类型,格式'*.jpg ...
- Build Telemetry for Distributed Services之OpenTracing简介
官网地址:https://opentracing.io/ What is Distributed Tracing? Who Uses Distributed Tracing? What is Open ...
- MySQL连接错误:Can't connect to MySQL server on'localhost' (10055)
在Windows服务器上确认服务器和mysql都是正常运行,但就是连接不上.搜了一下别人的解决方案, 参考这篇https://blog.csdn.net/langren697/article/deta ...
- python多线程、线程锁
1.python多线程 多线程可以把空闲时间利用起来 比如有两个进程函数 func1.func2,func1函数里使用sleep休眠一定时间,如果使用单线程调用这两个函数,那么会顺序执行这两个函数 也 ...
- redis watch 加 事务实现秒杀
<?php //redis watch 加 事务实现秒杀 $redis = new redis(); $result = $redis->connect('10.10.10.119 ...