物色到的 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( ...
随机推荐
- AtCoder Beginner Contest 211 (C ~ E) 个人题解
比赛链接:Here A.B题跳过 C - chokudai 题意: 给出一个字符串,问有多少个字串能构成 chokudai 这道题算是一个简单DP,只要计算某个位置对构成 chokudai 的贡献值即 ...
- Codeforces Round #565 (Div. 3) (重现赛个人题解)
1176A. Divide it! 题目链接:http://codeforces.com/problemset/problem/1176/A 题意: 给定一个数字 \(n\) 和三种操作 如果 n 能 ...
- ECS模式
大家好,本文提出了ECS模式.ECS模式是游戏引擎中常用的模式,通常用来组织游戏场景.本文出自我写的开源书<3D编程模式>,该书的更多内容请详见:Github 在线阅读 普通英雄和超级英雄 ...
- element-ui 实现行合并-亲测有效!
目标样式: 首先先来看下我们拿到的返回数据: scheduleList: [ { date: '第一天', journey: '报道', lecturer: '', }, { date: '第二天', ...
- babel相关配置
npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node npm install --save @babe ...
- wav文件头信息
概述 最近在对接百度TTS的python接口,对接的过程中发现一些问题,记录下解决方案. 百度TTS接口返回的音频数据格式有4种,分别是mp3,pcm-16k,pcm-8k,wav(pcm-16k). ...
- 【Linux API 揭秘】module_init与module_exit
[Linux API 揭秘]module_init与module_exit Linux Version:6.6 Author:Donge Github:linux-api-insides 1.函数作用 ...
- CSS - 工具类 tool.css
/* flex */ .flex{ display: flex; } .f1{ flex:1 } .flex-center{ align-items: center; ...
- [转帖]Linux基础之chkconfig systemd
https://www.cnblogs.com/barneywill/p/10461279.html CentOS6服务用chkconfig控制,CentOS7改为systemd控制 1 syst ...
- [转帖]k8s对接ceph,ceph-csi方式
1.上传ceph-csi-yaml和ceph-csi-image 两个文件夹到服务器 2.加载 ceph-csi-image里面的镜像 3.将加载好的镜像上传到本地harbor上. 4.修改ceph- ...