/// <summary>
/// POST方式提交 application/json
/// </summary>
/// <param name="postUrl">请求地址</param>
/// <param name="paramData">入参</param>
/// <param name="dataEncode">编码方式</param>
/// <returns></returns>
public string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
{
string ret = string.Empty;
try
{ byte[] byteArray = dataEncode.GetBytes(paramData); //转化
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
ServicePointManager.ServerCertificateValidationCallback = delegate(
Object obj, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return (true);
}; HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl)); webReq.Method = "POST";
webReq.ContentType = "application/json";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close(); }
catch (Exception ex)
{
MessageBoxs.ShowError(ex.Message);
}
return ret;
} /// <summary>
/// POST方式提交 application/json
/// </summary>
/// <param name="postUrl">请求地址</param>
/// <param name="paramData">入参</param>
/// <param name="dataEncode">编码方式</param>
/// <returns></returns>
public string PostWebRequest(string postUrl, string paramData)
{
string ret = string.Empty;
try
{ byte[] byteArray = Encoding.UTF8.GetBytes(paramData); //转化
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
ServicePointManager.ServerCertificateValidationCallback = delegate(
Object obj, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return (true);
};
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "application/json";
webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close(); }
catch (Exception ex)
{
MessageBoxs.ShowError(ex.Message);
} return ret;
} /// <summary>
/// POST方式提交 multipart/form-data
/// </summary>
/// <param name="postUrl">请求的拼接地址及入参(示例:http://ip:端口?a=1&b=2)</param>
/// <returns></returns>
public string PostRequest(string strInterFaceName, string postUrl)
{
string ret = string.Empty;
try
{
byte[] byteArray = Encoding.UTF8.GetBytes(postUrl); //转化
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
webReq.Method = "POST";
webReq.ContentType = "multipart/form-data"; webReq.ContentLength = byteArray.Length;
Stream newStream = webReq.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);//写入参数
newStream.Close();
HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
ret = sr.ReadToEnd();
sr.Close();
response.Close();
newStream.Close(); }
catch (Exception ex)
{
MessageBoxs.ShowError(ex.Message);
}
return ret;
} /// <summary>
/// Get提交方式
/// </summary>
/// <param name="getUrl">请求地址</param>
/// <returns></returns>
public string GetWebRequest(string getUrl)
{
string responseStr = string.Empty;
try
{ WebRequest myWebRequest = WebRequest.Create(getUrl);
WebResponse myWebResponse = myWebRequest.GetResponse();
Stream ReceiveStream = myWebResponse.GetResponseStream(); if (ReceiveStream != null)
{
StreamReader reader = new StreamReader(ReceiveStream, Encoding.UTF8);
responseStr = reader.ReadToEnd();
reader.Close();
}
myWebResponse.Close(); }
catch (Exception ex)
{ } return responseStr;
} /// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public string Post(string url)
{
string result = ""; ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
ServicePointManager.ServerCertificateValidationCallback = delegate(
Object obj, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return (true);
}; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
} /// <summary>
/// 发送JSON请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="json">请求JSON</param>
/// <param name="timeout">超时时间(秒)</param>
/// <returns>响应对象</returns>
public T PostJson<T>(string url, object json, int timeout = 10)
{
try
{
var jsonString = JsonConvert.SerializeObject(json);
var jsonBytes = Encoding.UTF8.GetBytes(jsonString);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
ServicePointManager.ServerCertificateValidationCallback = delegate(
Object obj, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return (true);
}; HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest; request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
request.ContentLength = jsonBytes.Length;
request.Timeout = timeout * 1000;
ServicePointManager.ServerCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => { return true; };
using (var writer = request.GetRequestStream())
{
writer.Write(jsonBytes, 0, jsonBytes.Length); HttpWebResponse response = request.GetResponse() as HttpWebResponse;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
throw new Exception(string.Format("请求失败:{0}", ex.Message));
}
} /// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public T DicPost<T>(string url, Dictionary<string, string> dic)
{
//string result = "";
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
ServicePointManager.ServerCertificateValidationCallback = delegate(
Object obj, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return (true);
}; req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region 添加Post 参数
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
JHLog.Instance().Writelog("builder:" + builder.ToString());
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
string result = reader.ReadToEnd();
JHLog.Instance().Writelog("响应内容:"+result);
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
}
}
catch (Exception ex)
{
throw new Exception(string.Format("请求失败:{0}", ex.Message));
}
} /// <summary>
/// 指定Post地址使用Get 方式获取全部字符串 application/x-www-form-urlencoded
///using System.Net.Security;
///using System.Security.Cryptography.X509Certificates;
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public string DicPosts(string url, Dictionary<string, string> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //一定要有这一句
ServicePointManager.ServerCertificateValidationCallback = delegate(
Object obj, X509Certificate certificate, X509Chain chain,
SslPolicyErrors errors)
{
return (true);
};
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region 添加Post 参数
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
} /// <summary>
/// POST请求与获取结果
/// 地址:http://ip:port?appid=11&dd=22&appkey=33
/// </summary>
public string HttpPostJson(string Url, string postDataStr)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json";
// request.ContentLength = postDataStr.Length;
StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.GetEncoding("utf-8"));
writer.Write(postDataStr);
writer.Flush();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
}

  

C# POST GET请求方式汇总的更多相关文章

  1. Asp.net页面间传值方式汇总

    七种传值方式,分别是:URL传值,Session传值,Cookie传值,Server.Transfer传值,Application传值,利用某些控件的PostBackUrl属性和使用@Previous ...

  2. Web 前端必备的各种跨域方式汇总

    Web 前端必备的各种跨域方式汇总 跨域方式汇总 同源策略 协议相同 + 域名相同 + 端口相同 https://www.xgqfrms.xyz/index.html https://www.xgqf ...

  3. 限制action所接受的请求方式或请求参数

    原文:http://www.cnblogs.com/liukemng/p/3726897.html 2.限制action所接受的请求方式(get或post): 之前我们在HelloWorldContr ...

  4. Android——JDK的get请求方式

    layout文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:an ...

  5. 第二节(RequestMapping请求方式)学习尚硅谷-springmvc视频教程

    项目中,创建测试类SpringMVCTest @Controller @RequestMapping("/springmvc1") public class SpringMVCTe ...

  6. jQuery中ajax的4种常用请求方式

    jQuery中ajax的4种常用请求方式: 1.$.ajax()返回其创建的 XMLHttpRequest 对象. $.ajax() 只有一个参数:参数 key/value 对象,包含各配置及回调函数 ...

  7. js中同步与异步请求方式

    异步请求方式: $.ajax({ url : 'your url', data:{name:value}, cache : false, async : true, type : "POST ...

  8. WEB API 中HTTP的get、post、put,delete 请求方式

    一.WEB API 中HTTP 请求方式的四个主要方法 (GET, PUT, POST, DELETE), 按照下列方式映射为 CURD 操作: 1.POST 用于新建资源,服务端在指定的URI 上创 ...

  9. Ajax中的get和post两种请求方式的异同

    Ajax中我们经常用到get和post请求.那么什么时候用get请求,什么时候用post方式请求呢? 在做回答前我们首先要了解get和post的区别.   1. get是把参数数据队列加到提交表单的A ...

  10. HTTP 请求方式: GET和POST的比较(转)

    GET和POST是HTTP的两个常用方法.   什么是HTTP? 超文本传输协议(HyperText Transfer Protocol -- HTTP)是一个设计来使客户端和服务器顺利进行通讯的协议 ...

随机推荐

  1. 使用shell定时执行脚本

    yum install crontabs //安装 #检查安装crontab -V #服务操作service crond start //启动服务service crond stop //关闭服务se ...

  2. 网线接口调试,Android ADB网络调试!

    ADB网络调试,网线接口调试    没有USB接口,照样可以调试,可通过网线接口调试步骤! 一.第一步连接WIFI  查看wifi 的IP  win+R 键 打开运行 ,输入cmd   二.输入ipc ...

  3. Andorid 悬浮窗的适配指北

    我们有时候需要显示一个悬浮窗,悬浮窗由服务开启,里面会有一些操作 但是我在开发时遇到高版本 Android12 和低版本4.4 ,显示不一样的地方 这边整理了下适配的方法方案 一:根据版本不一的时候, ...

  4. K8s试验环境搭建(一)

    一.kubernetes简介 1.什么是kubernetes? kubernetes是google公司用go语言开发的一套容器编排系统,简称k8s:它主要用于容器编排:所谓容器编排简单的我们可以理解为 ...

  5. python面向对象--类的刨析

    编程日常::::#编程就是程序员用特定的语法加数据结构加算法在计算机上执行过程,方式有很多种,最常用的就是面向对象编程和面向过程编程#设计思路一开始解决一个大问题,然后把大问题分解成小问题,一步步解决 ...

  6. redis过期事件监听

    1 修改 redis.conf配置文件: K Keyspace events, published with keyspace@ prefix事件 E Keyevent events, publish ...

  7. PC端 图片宽度是百分比,动态设置图片高度为 6:9

    我们知道图片宽度可以设置  百分比,但是高度要给一个固定值  不然不生效,并且产品要求图片显示必须是9:6,这开始确实难倒我了 后面想了一下用js  获取图片宽度  动态的计算高度就行了,超简单 se ...

  8. ctfshow web入门41

    这个题过滤了$.+.-.^.~使得异或自增和取反构造字符都无法使用,同时甚至过滤了字母和数字. 但是特意留了个或运算符|. 由此我们可以尝试从ascii为0-255的字符中,找到用或运算能得到我们可用 ...

  9. JS中有关(...)的介绍

    1,深拷贝一个对象 如上图所示,obj和tmp是完全两个独立的对象,互不影响. 2,数组复制 如上图所示,arr和tmp是两个完全独立的数组,彼此之间的值互不影响. 3,函数形参中的使用 这里的... ...

  10. 类Class

    C# 类(Class) 当你定义一个类时,你定义了一个数据类型的蓝图.这实际上并没有定义任何的数据,但它定义了类的名称意味着什么,也就是说,类的对象由什么组成及在这个对象上可执行什么操作.对象是类的实 ...