笔者最近有需求要爬取某一网站数据,原程序基于C#书写,因此为了运行速度,笔者基于C#书写了POST请求并进行传参操作。本文参考了目前网上部分的函数,但由于版本和传参问题,目前大部分均不能直接使用。本文基于HttpWebRequest进行了POST的请求操作,并基于目前大部分端口的参数设置,配置了json传参的操作。

一、依赖库安装

本文主要用到Newtonsoft.Json库,以下是安装步骤。

1.首先找到资源管理器,找到依赖项。

在这里插入图片描述

2.右击打开管理NuGet程序包。

在这里插入图片描述

3.搜索json,然后安装即可。因为笔者已安装,这里是更新。

在这里插入图片描述
在这里插入图片描述

二、实现代码

本文基于C#的窗体程序开发,首先加载依赖。

using System.Net;
using System.Text;;
using Newtonsoft.Json;

具体实现代码

 string result = "";
String url = "https://";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";//请求方式
req.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 6.1;WOW64) AppleWebKit/537.36 (KHTML,like GeCKO) Chrome/45.0.2454.85 Safari/537.36 115Broswer/6.0.3";
req.Headers["Connection"] = "keep-alive";
req.Headers["Transfer-Encoding"] = "chunked";
req.ContentType = "application/json; charset=UTF-8";//添加请求头
Dictionary<string, string> strList = new Dictionary<string, string>();
strList.Add("id", "value");
strList.Add("text", "text");
string mapStr = JsonConvert.SerializeObject(strList);//转换为json
byte[] data = Encoding.UTF8.GetBytes(mapStr);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
    reqStream.Write(data, 0, data.Length);
    reqStream.Close();
}
HttpWebResponse response = (HttpWebResponse)req.GetResponse();  //发送请求
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);//解析
string str = streamReader.ReadToEnd();//输出
GitHub 加速计划 / js / json
57
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:1 个月前 )
68c25aec * :memo: update customers Signed-off-by: Niels Lohmann <mail@nlohmann.me> * :memo: add badge to Cloudback Signed-off-by: Niels Lohmann <mail@nlohmann.me> --------- Signed-off-by: Niels Lohmann <mail@nlohmann.me> 3 天前
ac0133ea Bumps [mkdocs-git-revision-date-localized-plugin](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin) from 1.4.5 to 1.4.6. - [Release notes](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/releases) - [Commits](https://github.com/timvink/mkdocs-git-revision-date-localized-plugin/compare/v1.4.5...v1.4.6) --- updated-dependencies: - dependency-name: mkdocs-git-revision-date-localized-plugin dependency-version: 1.4.6 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 4 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐