#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. 程序猿必备的Git教程

    http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000 版权声明:本文为博主原创文章,未经 ...

  2. 【原创】FltGetFileNameInformation蓝屏分析

    FAULTING_IP: nt!SeCreateAccessStateEx+5b80564184 848788000000 test byte ptr [edi+88h],al TRAP_FRAME: ...

  3. 启动maven项目时报错Failed to start component [StandardEngine[Tomcat]]: A child container failed during start

    详细错误信息:Failed to execute goal org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run (default-cli) on ...

  4. 连接Android模拟器

    一.如何找到adb?    安装夜神安卓模拟器后,电脑桌面会有“夜神模拟器”的启动图标,鼠标右键--打开文件所在的位置,就会进入***\Nox\bin,默认路径是C:\Program Files (x ...

  5. Windows下MongoDB的安装过程及基本配置

    首先当然是到官网下载 MongoDB 了,点击进入后会看到下载页面,如下图所示: 安装有2种方式: 一种是通过直接点击下载的安装文件进行安装: 另一种是通过命令提示符来安装,下面我将直接通过第一种方式 ...

  6. Hype-v创建服务器实例

    1.创建虚拟交换机,如下图所示(虚拟交换机,只需要创建一次,后面增加服务器实例的时候,只需要选择这个虚拟交换机就可以了,不用每次都创建) 2.服务器主网络共享给虚拟交换机,如下图所 3.虚拟交换机的I ...

  7. HearthBuddy Ai 调试实战2 在使用海巨人的时候,少召唤了一个图腾(费用是对的)

    问题 游戏面板 8是青玉之爪13是海巨人17是恐狼前锋 64是萨满 66是圣骑士63,99,46,是微型木乃伊[其中99和46都是2血3攻,63是2血1攻]57是鱼人木乃伊 微型木乃伊 "L ...

  8. C# DumpBin使用 查看反射C++ dll 动态链接库中的函数

    DumpBin是Microsoft提供的一个用于查看.exe..dll文件信息的工具,其位于: C:\Program Files (x86)\Microsoft Visual Studio 10.0\ ...

  9. oracle 中SQL 语句开发语法 SELECT INTO含义

    oracle 中SQL 语句开发语法 SELECT INTO含义 在ORACLE中SELECT INTO是如何使用的,什么意思?和SQL SERVER的不一样?   和sqlserver的不一样sql ...

  10. swift 跳转到系统设置/网络/推送提醒

    使用App-Prefs做域跳转,代码如下: if let url = URL(string: "App-Prefs:root=NOTIFICATIONS_ID"), UIAppli ...