C# POST与Get数据
引用DLL
普通Get数据和Post数据
public static string Get(string URL)
{
String ReCode = string.Empty;
try
{
HttpWebRequest wNetr = (HttpWebRequest)HttpWebRequest.Create(URL);
HttpWebResponse wNetp = (HttpWebResponse)wNetr.GetResponse();
wNetr.ContentType = "text/html";
wNetr.Method = "Get";
Stream Streams = wNetp.GetResponseStream();
StreamReader Reads = new StreamReader(Streams, Encoding.UTF8);
ReCode = Reads.ReadToEnd(); //封闭临时不实用的资料
Reads.Dispose();
Streams.Dispose();
wNetp.Close();
}
catch (Exception ex) { throw ex; } return ReCode; } public static string Post(string url, string data)
{
string returnData = null;
try
{
//byte[] buffer = Encoding.UTF8.GetBytes(data);
//HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);
//webReq.Method = "POST";
//webReq.ContentType = "application/x-www-form-urlencoded";
//webReq.ContentLength = buffer.Length;
//Stream postData = webReq.GetRequestStream();
//webReq.Timeout = 99999999;
////webReq.ReadWriteTimeout = 99999999;
//postData.Write(buffer, 0, buffer.Length);
//postData.Close();
//HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
//Stream answer = webResp.GetResponseStream();
//StreamReader answerData = new StreamReader(answer);
//returnData = answerData.ReadToEnd(); string strURL = url;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
string paraUrlCoded = data;
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer = request.GetRequestStream();
writer.Write(payload, , payload.Length);
writer.Close();
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
returnData = strValue;
}
catch
{
return "获取错误";
}
return returnData.Trim() + "\n";
}
/// <summary>
/// 将json数据反序列化为Dictionary
/// </summary>
/// <param name="jsonData">json数据</param>
/// <returns></returns>
public static Dictionary<string, object> JsonToDictionary(string jsonData)
{
//实例化JavaScriptSerializer类的新实例。。。需要添加 System.Web.Extensions引用
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
//将指定的 JSON 字符串转换为 Dictionary<string, object> 类型的对象
return jss.Deserialize<Dictionary<string, object>>(jsonData);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
HTTPS POST
class ProgramTest
{
static void Main(string[] args)
{
string url = "https://www.test.com";
string result = PostUrl(url, "key=123"); // key=4da4193e-384b-44d8-8a7f-2dd8b076d784
Console.WriteLine(result);
Console.WriteLine("OVER");
Console.ReadLine();
} private static string PostUrl(string url, string postData)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request.ProtocolVersion = HttpVersion.Version11;
// 这里设置了协议类型。
ServicePointManager.SecurityProtocol = (SecurityProtocolType);// SecurityProtocolType.Tls1.2;
request.KeepAlive = false;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = ;
ServicePointManager.Expect100Continue = false;
}
request.Method = "POST"; //使用get方式发送数据
request.ContentType = "application/x-www-form-urlencoded";
request.Referer = null;
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Accept = "*/*"; byte[] data = Encoding.UTF8.GetBytes(postData);
Stream newStream = request.GetRequestStream();
newStream.Write(data, , data.Length);
newStream.Close(); //获取网页响应结果
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
//client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string result = string.Empty;
using (StreamReader sr = new StreamReader(stream))
{
result = sr.ReadToEnd();
} return result;
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
}
附.另外一个Post
public void Post()
{
var d = new SendNews();
d.touser = touser;
d.agentid = "";
d.Description = wxmsg; HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:47870/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = client.PostAsJsonAsync("api/SendMsg/SendNews", d).Result;
} public class SendNews
{
/// <summary>
/// UserID列表(消息接收者,多个接收者用‘|’分隔)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送
/// </summary>
public string touser { get; set; }
/// <summary>
/// PartyID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数
/// </summary>
public string toparty { get; set; }
/// <summary>
/// TagID列表,多个接受者用‘|’分隔。当touser为@all时忽略本参数
/// </summary>
public string totag { get; set; }
/// <summary>
/// 消息类型
/// </summary>
public string msgtype { get; set; }
/// <summary>
/// 企业应用的id,整型。可在应用的设置页面查看
/// </summary>
public string agentid { get; set; } /// <summary>
/// 表示是否是保密消息,0表示否,1表示是,默认0
/// </summary>
public string safe { get; set; } /// <summary>
/// 文章标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 文章描述
/// </summary>
public string Description { get; set; }
/// <summary>
/// 图片链接,支持JPG、PNG格式,较好的效果为大图360*200,小图200*200
/// </summary>
public string PicUrl { get; set; }
/// <summary>
/// 点击图文消息跳转链接
/// </summary>
public string Url { get; set; }
}
键值对提交
//重点!! 成功 利用Webclient Post 按字段的方式提交每个字段的内容给服务器端
public string WebClientPost(string url, System.Collections.Specialized.NameValueCollection PostVars)
{
try
{
System.Net.WebClient WebClientObj = new System.Net.WebClient();
byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", PostVars);
//下面都没用啦,就上面一句话就可以了
string sRemoteInfo = System.Text.Encoding.Default.GetString(byRemoteInfo);
return sRemoteInfo; }
catch
{
return "";
}
} public void test()
{
System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
PostVars.Add("test", "value");
PostVars.Add("cmd", "value");
PostVars.Add("token", "value");
WebClientPost("url", PostVars);
}
C# POST与Get数据的更多相关文章
- Hadoop 中利用 mapreduce 读写 mysql 数据
Hadoop 中利用 mapreduce 读写 mysql 数据 有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 pv.uv 数据,然后为了实时查询的需求,或者一些 OLAP ...
- App开发:模拟服务器数据接口 - MockApi
为了方便app开发过程中,不受服务器接口的限制,便于客户端功能的快速测试,可以在客户端实现一个模拟服务器数据接口的MockApi模块.本篇文章就尝试为使用gradle的android项目设计实现Moc ...
- 使用TSQL查询和更新 JSON 数据
JSON是一个非常流行的,用于数据交换的文本数据(textual data)格式,主要用于Web和移动应用程序中.JSON 使用“键/值对”(Key:Value pair)存储数据,能够表示嵌套键值对 ...
- SQL Server 大数据搬迁之文件组备份还原实战
一.本文所涉及的内容(Contents) 本文所涉及的内容(Contents) 背景(Contexts) 解决方案(Solution) 搬迁步骤(Procedure) 搬迁脚本(SQL Codes) ...
- SQLSERVER将一个文件组的数据移动到另一个文件组
SQLSERVER将一个文件组的数据移动到另一个文件组 有经验的大侠可以直接忽视这篇文章~ 这个问题有经验的人都知道怎麽做,因为我们公司的数据量不大没有这个需求,也不知道怎麽做实验 今天求助了QQ群里 ...
- 【.net 深呼吸】设置序列化中的最大数据量
欢迎收看本期的<老周吹牛>节目,由于剧组严重缺钱,故本节目无视频无声音.好,先看下面一个类声明. [DataContract] public class DemoObject { [Dat ...
- Scrapy框架爬虫初探——中关村在线手机参数数据爬取
关于Scrapy如何安装部署的文章已经相当多了,但是网上实战的例子还不是很多,近来正好在学习该爬虫框架,就简单写了个Spider Demo来实践.作为硬件数码控,我选择了经常光顾的中关村在线的手机页面 ...
- 通过AngularJS实现前端与后台的数据对接(二)——服务(service,$http)篇
什么是服务? 服务提供了一种能在应用的整个生命周期内保持数据的方法,它能够在控制器之间进行通信,并且能保证数据的一致性. 服务是一个单例对象,在每个应用中只会被实例化一次(被$injector实例化) ...
- 恢复SQL Server被误删除的数据(再扩展)
恢复SQL Server被误删除的数据(再扩展) 大家对本人之前的文章<恢复SQL Server被误删除的数据> 反应非常热烈,但是文章里的存储过程不能实现对备份出来的日志备份里所删数据的 ...
- 将表里的数据批量生成INSERT语句的存储过程 增强版
将表里的数据批量生成INSERT语句的存储过程 增强版 有时候,我们需要将某个表里的数据全部或者根据查询条件导出来,迁移到另一个相同结构的库中 目前SQL Server里面是没有相关的工具根据查询条件 ...
随机推荐
- linux添加字体的过程
只说一下过程, 至于具体的原理还没搞明白. 1. 首先你要有字体文件,ttf或者ttc格式的均可以 我们可以从windows的 C:\WINDOWS\Fonts\ 这个目录下的字体文件复制出来,例如我 ...
- C#抽象类及其方法的学习【转】
转至 http://www.cnblogs.com/flyinthesky/archive/2008/06/18/1224774.html 在C#中使用关键字 abstract 来定义抽象类和抽象方法 ...
- ==,equal,hasCode(),identifyHasCode()浅析
在java中如果我们要比较两个对象之间的关系的话有可能会用到下面的几种方法:==,equal,hasCode(),identifyHasCode(). ==用来比较对象本身是不是相同的. public ...
- 一个基于和围绕Docker生态环境构建的早期项目列表
https://blog.docker.com/2013/07/docker-projects-from-the-docker-community/
- Spring+Mybatis整合报错Mapped Statements collection does not contain value原因之一
报错如下: ### Error updating database. Cause: java.lang.IllegalArgumentException: Mapped Statements coll ...
- windows win10上传文件到linux服务器
1.最直接当然使用终端secucrt和xshell putty之类的,然后使用sz rz 2.如果服务器端不支持sz rz可以使用scp命令,下面这个pscp.exe就是支持scp的,基于ssh,很好 ...
- JavaScript中统计Textarea字数并提示还能输入的字符
<span style="font-size:18px;"><script language="javascript"> functio ...
- ALTFP_CONVERT IP使用与仿真
ALTFP_CONVERT IP使用与仿真 近期项目要使用到整型数据转浮点型数据,将16位的整数转换为单精度浮点数(32bit).本打算自己写逻辑实现的,不过考虑到本身项目时间紧,能力也有限,就没 ...
- 关于PHP的正则表达式
1.入门简介 简单的说,正则表达式是一种可以用于模式匹配和替换的强有力的工具.我们可以在几乎所有的基于UNIX系统的工具中找到正则表达式的身影,例如,vi编辑器,Perl或PHP脚本语言,以及awk或 ...
- C#.Net理论
-------------2014年8月28---------------------------- 1.C#的委托是什么,事件是不是一种委托?答:委托可以把一个方法作为参数代入另一个方法.委托可以理 ...