api post 请求纪要

不用抓包工具,返回错误信息不够全面,在此次测试中也就返回了status的415 和error错误  ,而没有类似下边wireshark抓包返回的信息 还隐藏着message这个信息

{"timestamp":"2020-08-27T03:51:50.524+0000","status":415,"error":"Unsupported Media Type","message":"Invalid mime type \"Content-Type: application/json\": Invalid token character ‘:‘ in token \"Content-Type: application\"","path":"/app/user/login"}HTTP/1.1 100 Continue

尽管上边你的415提示的是媒体格式问题,因为还有json格式,以及对post 的使用不够深刻,也没进一步锁定问题,最终通过上边出现的 Content-Type,发现方法里边的 配置出现问题

正确: request.ContentType = "application/json";

错误: request.ContentType = "Content-Type: application/json";  //重复的写了content-type

出现报错

粘来粘去的代码,一不留神就出了问题

fiddler 抓web 包 抓不着软件里边的请求,所以改用wireshark

技术图片

 

 技术图片

 

 正确的返回

技术图片

 

 request.ContentType = "application/json"; 类型的post请求方法

 /// <summary> /// 向指定 URL 发送POST方法的请求 /// </summary> /// <param name="url">发送请求的 URL</param> /// <param name="jsonData">请求参数,请求参数应该是Json格式字符串的形式。</param> /// <returns>所代表远程资源的响应结果</returns> public static string SendPost(string url, string jsonData) { string result = String.Empty; try { CookieContainer cookie = new CookieContainer(); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; //request.Headers.Add("x-requested-with", "XMLHttpRequest"); //request.ServicePoint.Expect100Continue = false; request.ContentType = "application/json"; request.Accept = "application/json"; //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"; request.ContentLength = Encoding.UTF8.GetByteCount(jsonData); request.CookieContainer = cookie; using (StreamWriter writer = new StreamWriter(request.GetRequestStream())) { writer.Write(jsonData); } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); response.Cookies = cookie.GetCookies(response.ResponseUri); using (Stream responseStream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { result = reader.ReadToEnd(); reader.Close(); } responseStream.Close(); } response.Close(); response = null; request = null; } catch (Exception ex) { Console.WriteLine("发送GET请求出现异常:" + ex.Message); } return result; }

参数 jsonData 可以先定义一个实体类 通过 JsonConvert.SerializeObject(lg);  转换成json 格式

string jslg= JsonConvert.SerializeObject(lg); 
string result= SendPost(url, jslg);

相关文章