度量快速开发平台-专业、快速的软件定制快开平台

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: 部件 流程 SQL
查看: 2712|回复: 1
打印 上一主题 下一主题

[分享] C#Http请求

[复制链接]

182

主题

2120

帖子

4842

积分

论坛元老

Rank: 8Rank: 8

积分
4842
跳转到指定楼层
楼主
发表于 2020-3-19 17:41:17 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
string param = "<xml>"
+"<ToUserName><![CDATA[toUser]]></ToUserName>"
+"<FromUserName><![CDATA[fromUser]] ></FromUserName>"
+"<CreateTime> 1348831860 </CreateTime>"
+"<MsgType><![CDATA[text]] ></MsgType>"
+"<Content><![CDATA[this is a test]] ></Content>"
+"<MsgId> 1234567890123456 </MsgId>"
+"</xml> ";

//编码格式
Encoding encoding = Encoding.GetEncoding("UTF-8");
byte[] bs = encoding.GetBytes(param);

string text2 = string.Format("http://localhost:52827/api/Wx");

HttpWebRequest httpWebRequest = WebRequest.CreateHttp(text2);
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = bs.Length;

using (Stream reqStream = httpWebRequest.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
reqStream.Flush();
reqStream.Close();
}
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
HttpWebResponse response = null;
try
{

using (StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream(), encoding))
{
while (streamReader.Peek() != -1)
{
string text = streamReader.ReadLine() + "\r\n";
}
}

}
catch (WebException ex)
{
if (ex.Response != null) //不正确的状态码
{
text = (HttpWebResponse)ex.Response;

}
}
catch (Exception ex)
{
//其他异常,连状态码都没能获取
throw ex;

}



/// <summary>
/// 调用WebApi获取数据
/// </summary>
/// <param name="msgModel">获取xxx对象的数据(WebApi中的方法名)</param>
/// <param name="param">需要传递的参数名字和值</param>
/// <returns>json数据</returns>
public static string GetMsg(string msgModel, string param)
{

if (string.IsNullOrWhiteSpace(msgModel))
{
return string.Empty;
}
string result = string.Empty;
string path = AppSetting.WEBAPI_ADDRESS + msgModel + param;
Uri resourceUri = new Uri(path);
HttpClientHandler handler = new HttpClientHandler();
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(300));
handler.AllowAutoRedirect = false;//是否应该跟随重定向相应
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;//使用客户端证书(应用的证书储存区自动选择最佳匹配的证书用于验证)
handler.UseProxy = false;//不适用代理
handler.UseDefaultCredentials = true;//是否使用默认用户验证
HttpClient httpclient = new HttpClient(handler);
httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = httpclient.GetAsync(resourceUri, cts.Token).Result;
if (response.EnsureSuccessStatusCode().IsSuccessStatusCode == true)
{
result = response.Content.ReadAsStringAsync().Result;
}
}
catch (TaskCanceledException ex)
{
// 因超时取消请求的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "GetMsg", ex.Message, ex.StackTrace);
}
catch (HttpRequestException ex)
{
// 处理其它可能异常的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "GetMsg", ex.Message, ex.StackTrace);
}
catch (Exception ex)
{
// 处理其它可能异常的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "GetMsg", ex.Message, ex.StackTrace);
}
return result;
}





/// <summary>
/// 调用WebApi发送post数据
/// </summary>
/// <param name="msgModel">发送xxx对象的数据(WebApi中的方法名)</param>
/// <param name="jsonData">需要发送的json数据</param>
/// <param name="paramName">需要传递的参数名字</param>
/// <returns>WebApi是否接收成功(success/fail/error)</returns>
public static string PostMsg(string msgModel, string jsonData, string paramName)
{
if (string.IsNullOrWhiteSpace(msgModel))// || string.IsNullOrWhiteSpace(jsonData)
{
return string.Empty;
}

string result = string.Empty;
string path = AppSetting.WEBAPI_ADDRESS + msgModel + paramName;
HttpClientHandler handler = new HttpClientHandler();
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(300));
handler.AllowAutoRedirect = false;//是否应该跟随重定向相应
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;//使用客户端证书(应用的证书储存区自动选择最佳匹配的证书用于验证)
handler.UseProxy = false;//不适用代理
handler.UseDefaultCredentials = true;//是否使用默认用户验证
HttpClient httpclient = new HttpClient(handler);
httpclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
Uri resourceUri = new Uri(path + jsonData);
//HttpResponseMessage response = httpclient.GetAsync(resourceUri, cts.Token).Result;
HttpResponseMessage response = httpclient.PostAsync(resourceUri, new StringContent(jsonData), cts.Token).Result;
if (response.EnsureSuccessStatusCode().IsSuccessStatusCode == true)
{
result = response.Content.ReadAsStringAsync().Result;
}
}
catch (TaskCanceledException ex)
{
// 因超时取消请求的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "PostMsg", ex.Message, ex.StackTrace);
}
catch (HttpRequestException ex)
{
// 处理其它可能异常的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "PostMsg", ex.Message, ex.StackTrace);
}
catch (Exception ex)
{
// 处理其它可能异常的逻辑
result = string.Empty;
cts.Cancel();
cts.Dispose();
handler.Dispose();
httpclient.Dispose();
WriteLog("AppSetting-Class", "PostMsg", ex.Message, ex.StackTrace);
}
return result;
}

public string PostXml(string url, string strPost)
{
string result = "";

StreamWriter myWriter = null;
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Method = "POST";
//objRequest.ContentLength = strPost.Length;
objRequest.ContentType = "text/xml";//提交xml
//objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
try
{
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(strPost);
}
catch (Exception e)
{
return e.Message;
}
finally
{
myWriter.Close();
}

HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
{
result = sr.ReadToEnd();
sr.Close();
}
return result;
}

分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏
回复

使用道具 举报

182

主题

2120

帖子

4842

积分

论坛元老

Rank: 8Rank: 8

积分
4842
沙发
 楼主| 发表于 2020-3-19 17:41:55 | 只看该作者
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

手机版|小黑屋|玉祥公司客服-玉祥集团客服  本站关键词:快速开发平台

GMT+8, 2024-5-6 02:08 , Processed in 0.117847 second(s), 26 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表