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里面是没有相关的工具根据查询条件 ...
随机推荐
- zw版【转发·台湾nvp系列Delphi例程】HALCON DivImage1
zw版[转发·台湾nvp系列Delphi例程]HALCON DivImage1 procedure TForm1.Button1Click(Sender: TObject);var img0, ...
- JNI 回调小记
javah在eclipse中设置参数:location(javah.exe的位置)working dir(${project_loc}/src) -classpath .;./classes -d $ ...
- 华为项目管理10大模板Excel版(可直接套用_非常实用)
项目管理是管理学的一个分支学科 ,对项目管理的定义是:指在项目活动中运用专门的知识.技能.工具和方法,使项目能够在有限资源限定条件下,实现或超过设定的需求和期望的过程.项目管理是对一些与成功地达成一系 ...
- iOS delegate, 代理/委托与协议.
之前知知道iOS协议怎么写, 以为真的跟特么java接口一样, 后来发现完全不是. 首先, 说说应用场景, 就是当你要用一个程序类, 或者说逻辑类, 去控制一个storyboard里面的label, ...
- 【翻译】了解ASP.NET MVC的HTML助手
原文:Understanding HTML Helpers in ASP.NET MVC 作 者:Shailendra Chauhan works as Software Analyst at rep ...
- java中IO流操作的标准异常类
package 加入异常处理的字节流操作; import java.io.FileNotFoundException; import java.io.FileOutputStream; import ...
- iOS抓包Charles 操作
今天就来看一下Mac上如何进行抓包,之前有一篇文章介绍了使用Fidder进行抓包 http://blog.csdn.net/jiangwei0910410003/article/details/198 ...
- 关于匿名类无法转换为object
缘由,不能在Razor中使用匿名类, 先事先封装了一个方法,用于Razor给cshtml模板返回页面. 在ashx一般处理程序中,是这样调用的 匿名类的格式如下:(只看格式,不看具体内容) 调用这样 ...
- easyui 布局标题纵向排列
(function($){ var buttonDir = {north:'down',south:'up',east:'left',west:'right'}; ...
- BLOB:大数据,大对象,在数据库中用来存储超长文本的数据,例如图片等
将一张图片存储在mysql中,并读取出来(BLOB数据:插入BLOB类型的数据必须使用PreparedStatement,因为插入BLOB类型的数据无法使用字符串拼写): -------------- ...