物色到的 c# 模拟 http post get 请求 做下笔记
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Xfrog.Net;
using System.Diagnostics;
using System.Web; namespace ConsoleAPI
{
class Program
{
static void Main(string[] args)
{
string appkey = "*******************"; //配置您申请的appkey string url1 = ""; var parameters1 = new Dictionary<string, string>(); parameters1.Add("com" , "");
parameters1.Add("no" , "");
parameters1.Add("key", appkey);
parameters1.Add("dtype" , ""); //返回数据的格式,xml或json,默认json string result1 = sendPost(url1, parameters1, "get"); JsonObject newObj1 = new JsonObject(result1);
String errorCode1 = newObj1["error_code"].Value; if (errorCode1 == "0")
{
Debug.WriteLine("成功");
Debug.WriteLine(newObj1);
}
else
{
//Debug.WriteLine("失败");
Debug.WriteLine(newObj1["error_code"].Value+":"+newObj1["reason"].Value);
} //2.快递公司编号对照表
string url2 = "http://v.juhe.cn/exp/com"; var parameters2 = new Dictionary<string, string>(); string result2 = sendPost(url2, parameters2, "get"); JsonObject newObj2 = new JsonObject(result2);
String errorCode2 = newObj2["error_code"].Value; if (errorCode2 == "0")
{
Debug.WriteLine("成功");
Debug.WriteLine(newObj2);
}
else
{
//Debug.WriteLine("失败");
Debug.WriteLine(newObj2["error_code"].Value+":"+newObj2["reason"].Value);
} } /// <summary>
/// Http (GET/POST)
/// </summary>
/// <param name="url">请求URL</param>
/// <param name="parameters">请求参数</param>
/// <param name="method">请求方法</param>
/// <returns>响应内容</returns>
static string sendPost(string url, IDictionary<string, string> parameters, string method)
{
if (method.ToLower() == "post")
{
HttpWebRequest req = null;
HttpWebResponse rsp = null;
System.IO.Stream reqStream = null;
try
{
req = (HttpWebRequest)WebRequest.Create(url);
req.Method = method;
req.KeepAlive = false;
req.ProtocolVersion = HttpVersion.Version10;
req.Timeout = 5000;
req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
byte[] postData = Encoding.UTF8.GetBytes(BuildQuery(parameters, "utf8"));
reqStream = req.GetRequestStream();
reqStream.Write(postData, 0, postData.Length);
rsp = (HttpWebResponse)req.GetResponse();
Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
return GetResponseAsString(rsp, encoding);
}
catch (Exception ex)
{
return ex.Message;
}
finally
{
if (reqStream != null) reqStream.Close();
if (rsp != null) rsp.Close();
}
}
else
{
//创建请求
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "?" + BuildQuery(parameters, "utf8")); //GET请求
request.Method = "GET";
request.ReadWriteTimeout = 5000;
request.ContentType = "text/html;charset=UTF-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); //返回内容
string retString = myStreamReader.ReadToEnd();
return retString;
}
} /// <summary>
/// 组装普通文本请求参数。
/// </summary>
/// <param name="parameters">Key-Value形式请求参数字典</param>
/// <returns>URL编码后的请求数据</returns>
static string BuildQuery(IDictionary<string, string> parameters, string encode)
{
StringBuilder postData = new StringBuilder();
bool hasParam = false;
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
while (dem.MoveNext())
{
string name = dem.Current.Key;
string value = dem.Current.Value;
// 忽略参数名或参数值为空的参数
if (!string.IsNullOrEmpty(name))//&& !string.IsNullOrEmpty(value)
{
if (hasParam)
{
postData.Append("&");
}
postData.Append(name);
postData.Append("=");
if (encode == "gb2312")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.GetEncoding("gb2312")));
}
else if (encode == "utf8")
{
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
}
else
{
postData.Append(value);
}
hasParam = true;
}
}
return postData.ToString();
} /// <summary>
/// 把响应流转换为文本。
/// </summary>
/// <param name="rsp">响应流对象</param>
/// <param name="encoding">编码方式</param>
/// <returns>响应文本</returns>
static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
{
System.IO.Stream stream = null;
StreamReader reader = null;
try
{
// 以字符流的方式读取HTTP响应
stream = rsp.GetResponseStream();
reader = new StreamReader(stream, encoding);
return reader.ReadToEnd();
}
finally
{
// 释放资源
if (reader != null) reader.Close();
if (stream != null) stream.Close();
if (rsp != null) rsp.Close();
}
}
}
}
物色到的 c# 模拟 http post get 请求 做下笔记的更多相关文章
- 模拟ajax的 script请求
/** * 模拟ajax的 script请求 * @param {[type]} options [description] * @return {[type]} [description] */ f ...
- .net后台模拟浏览器get/post请求
#region 后台模拟浏览器get/post请求 /// <summary> /// 发送请求方式 /// </summary> /// <param name=&qu ...
- jQuery模拟原生态App上拉刷新下拉加载
jQuery模拟原生态App上拉刷新下拉加载效果代码,鼠标上拉时会显示loading字样,并且会模拟加载一条静态数据,支持触屏设备使用. <!doctype html> <html ...
- 模拟POST、Get 请求的工具----APIpost(中文版POSTMAN)
模拟POST.Get 请求的工具----APIpost(中文版POSTMAN) 快速生成.一键导出api文档 在线模拟调试,结果实时返回 模拟登录后请求API 支持团队协作 官网:https://ww ...
- Postman模拟Request Payload发送请求
Postman模拟Request Payload发送请求,如下图所示:
- 使用postman模拟appium的http请求
Appium是Server,接收http请求,使用Postman模拟请求 1.anyproxy 1.1.安装和运行 #安装 npm i -g anyproxy # 运行anyproxy,端口默认800 ...
- php中模拟post,get请求和接受请求详细讲解
在php中我们经常用到curl拓展来进行模拟post.get请求,下面就来具体说说怎么模拟: 一.首先模拟post请求: function http_post_data($url, $query_da ...
- JZOJ 5818. 【NOIP提高A组模拟2018.8.15】 做运动
5818. [NOIP提高A组模拟2018.8.15] 做运动 (File IO): input:running.in output:running.out Time Limits: 2000 ms ...
- Fiddler使用方法之Fiddler显示IP,Fiddler中文乱码解决方法以及Fiddler模拟发送get/post请求
Fiddler是一个HTTP的调试代理,以代理服务器的方式,监听系统的Http网络数据流动,是我们常用的抓包工具之一 今天为大家分享一下几个使用Fiddler的小技巧 一.Fiddler抓包中文乱码问 ...
- [Python] Python 模拟登录,并请求
Python 模拟登录,并请求 # encoding: utf- import requests import socket import time socket.setdefaulttimeout( ...
随机推荐
- Codeforece : 1360C. Similar Pairs(水题)
https://codeforces.com/contest/1360/problem/C We call two numbers xx and yy similar if they have the ...
- L2-020 功夫传人 (25分)
分析: ⽤⼆维数 组v存储师⻔谱系关系,v[i]表示编号为i的师傅所拥有的徒弟,如果徒弟个数等于0, 也就是说这是个得道者,那么v[i][0]保存放⼤的倍数,⽽且⽤visit[i] = true标记当 ...
- <vue 基础知识 3、v-bind使用>
代码结构 一. v-bind基本使用 1.效果 2.代码 01-v-bind基本使用.html <!DOCTYPE html> <html lang="en&quo ...
- SpringBoot 动态数据源
SpringBoot 实现动态数据源切换 Spring Boot + Mybatis Plus + Druid + MySQL 实现动态数据源切换及动态 SQL 语句执行. 项目默认加载 applic ...
- NLP复习之神经网络
NLP复习之神经网络 前言 tips: 设计神经网络时,输入层与输出层节点数往往固定,中间层可以自由指定: 神经网络中的拓扑与箭头代表预测过程数据流向,与训练的数据流有一定区别: 我们不妨重点关注连接 ...
- Redis 使用 hyperLogLog 实现请求ip去重的浏览量
本文为博主原创,转载请注明出处: 未完,待续....
- C#对象二进制序列化优化:位域技术实现极限压缩
目录 1. 引言 2. 优化过程 2.1. 进程对象定义与初步分析 2.2. 排除Json序列化 2.3. 使用BinaryWriter进行二进制序列化 2.4. 数据类型调整 2.5. 再次数据类型 ...
- DC-设计和工艺数据-02
在 compile之前保存ddc设计文件 check design - 检查文件的连接性和物理性 check design之后可以将未映射的网表写出,如果是几十万级的RTL,如果不写出,设置约束出现问 ...
- 关于spring-boot-starter-parent 3.1.2和3.1.5版本的区别导致的错误
1.问题 在学习黑马程序员SpringBoot3+Vue3全套视频教程时,手动配置springboot项目时,由于之前spring-boot-starter-parent安装的版本是3.1.5,视频要 ...
- Hexo中引入另一个文件内容
有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准https://blog.zysicyj.top 首发博客地址 安装插件 npm install hexo-include-m ...