C#发起HTTP请求
浏览器能看到的数据 用后端模拟请求都能获取到 如果拿不到 看看是不是请求参数哪里没设置 刚好服务器检查了这个参数
string url = ""; string para = ""; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);//创建请求对象 request.Method = "Post";//请求方式 request.KeepAlive = true; request.ContentType = "application/json";//请求头参数 byte[] bytes = System.Text.Encoding.UTF8.GetBytes(para);//设置请求参数 request.ContentLength = bytes.Length; Stream stream = request.GetRequestStream(); stream.Write(bytes, 0, bytes.Length);//写入参数 stream.Close(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())//响应对象 { StreamReader reader = new StreamReader(response.GetResponseStream()); string str = reader.ReadToEnd();//获取返回的页面信息 //根据返回的格式 创建一个对象 把Json反序列化成对应的类型对象 //反序列化的时候需要先创建一个模型来存放数据 Dto dto = JsonConvert.DeserializeObject<Dto>(str); }
设置请求头参数
request.Headers.Add("Accept", "*/*"); request.Headers.Add("Accept-Encoding", "gzip, deflate, sdch"); request.Headers.Add("Accept-Language", "zh-CN,zh;q=0.9"); request.KeepAlive = true; // request.Connection = "keep-alive"; // request.Headers.Add("Cookie", ""); request.Host = "sshhbhaokn.jin10.com:8083"; request.Headers.Add("Referer", "https://hero.jin10.com/"); request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36";
在f12的元素上 右键 copy Xpath 可以拷贝出当前元素的位置
/*************************
获取token请求
1. 用上面那种把参数先转成字节才写入会报错
2.设置请求头长度也会报错