#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题目300.最长上升子序列(动态规划-中等)

    题目描述: 给定一个无序的整数数组,找到其中最长上升子序列的长度. 示例: 输入: [10,9,2,5,3,7,101,18] 输出: 4 解释: 最长的上升子序列是 [2,3,7,101],它的长度 ...

  2. mysql -- 清空表中数据

    删除表信息的方式有两种 :truncate table table_name;delete * from table_name;注 : truncate操作中的table可以省略,delete操作中的 ...

  3. VGG Net学习笔记

    一.简介 VGG Net由牛津大学的视觉几何组(Visual Geometry Group)和 Google DeepMind公司的研究员一起研发的的深度卷积神经网络,在 ILSVRC 2014 上取 ...

  4. 前端知识点回顾——Reactjs

    React.js 编写react需要安装的三个开发环境下的模块 babel 解析JSX react 实现ui用户界面 react-dom 处理dom JSX:在JavaScript里面写html代码( ...

  5. SQL-W3School-高级:SQL Date 函数

    ylbtech-SQL-W3School-高级:SQL Date 函数 1.返回顶部 1. SQL 日期 当我们处理日期时,最难的任务恐怕是确保所插入的日期的格式,与数据库中日期列的格式相匹配. 只要 ...

  6. python select模块

    Python select 一.前言 Python的select()方法直接调用操作系统的IO接口,它监控sockets,open files, and pipes(所有带fileno()方法的文件句 ...

  7. python3 枚举enum定义和使用

    两种方式定义枚举类: 1.直接使用Enum列出多个枚举值来创建枚举类. 2.通过集成Enum基类派生枚举类. 程序示范: 1.直接使用Enum列出多个枚举值来创建枚举类. from enum impo ...

  8. java+大文件分段上传

    一. 功能性需求与非功能性需求 要求操作便利,一次选择多个文件和文件夹进行上传:支持PC端全平台操作系统,Windows,Linux,Mac 支持文件和文件夹的批量下载,断点续传.刷新页面后继续传输. ...

  9. MYSQL的MYSQLDUMP命令

    1.用mysqldump对MySQL数据库进行数据备份与恢复 下面假设要备份tm这个数据库:Shell>mysqldump -uroot –p123456 tm > tm_050519.s ...

  10. node.js运行内存堆溢出的解决办法

    我是在将一组80多列13万多行的数据通过node-xlsx的时候出现的内存堆溢出的情况. 解决办法时将: node app.js 改成: node --max_old_space_size=10000 ...