起因
很多博客都有描述到这个问题,那么为什么我还要写一篇文章来说一下呢,因为其他的都似乎已经过时了,会导致其实body 并没有发送过去。至于为什么不使用其他的诸如 HttpClient 之类的,是由于业务需要。
原来的处理方式
通过 GetRequestStream 来获取请求流,后把需要发送的 Json 数据写入到流中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
private T PostDataViaHttpWebRequest<T>( string baseUrl, IReadOnlyDictionary< string , string > headers, IReadOnlyDictionary< string , string > urlParas, string requestBody= null ) { var resuleJson = string .Empty; try { var apiUrl = baseUrl; if (urlParas != null ) urlParas.ForEach(p => { if (apiUrl.IndexOf( "{" + p.Key + "}" ) > -1) { apiUrl = apiUrl.Replace( "{" + p.Key + "}" , p.Value); } else { apiUrl += string .Format( "{0}{1}={2}" , apiUrl.Contains( "?" ) ? "&" : "?" , p.Key, p.Value); } } ); var req = (HttpWebRequest)WebRequest.Create(apiUrl); req.Method = "POST" ; req.ContentType = "application/json" ; req.ContentLength = 0; if (!requestBody.IsNullOrEmpty()) { using (var postStream = req.GetRequestStream()) { var postData = Encoding.ASCII.GetBytes(requestBody); req.ContentLength = postData.Length; postStream.Write(postData, 0, postData.Length); } } if (headers != null ) { if (headers.Keys.Any(p => p.ToLower() == "content-type" )) req.ContentType = headers.SingleOrDefault(p => p.Key.ToLower() == "content-type" ).Value; if (headers.Keys.Any(p => p.ToLower() == "accept" )) req.Accept = headers.SingleOrDefault(p => p.Key.ToLower() == "accept" ).Value; } var response = (HttpWebResponse)req.GetResponse(); using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding( "UTF-8" ))) { resuleJson = reader.ReadToEnd(); } } } catch (Exception ex) { return default (T); } return JsonConvert.DeserializeObject<T>(resuleJson); } |
但是会发现,数据一直没有正常发送过去,而且代码还显得比较复杂
新的方式
这里修改一下写入 RequestStream 的方式,使用 StreamWriter 包装一下,然后直接写入需要发送的 Json 数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
private T PostDataViaHttpWebRequest<T>( string baseUrl, IReadOnlyDictionary< string , string > headers, IReadOnlyDictionary< string , string > urlParas, string requestBody= null ) { var resuleJson = string .Empty; try { var apiUrl = baseUrl; if (urlParas != null ) urlParas.ForEach(p => { if (apiUrl.IndexOf( "{" + p.Key + "}" ) > -1) { apiUrl = apiUrl.Replace( "{" + p.Key + "}" , p.Value); } else { apiUrl += string .Format( "{0}{1}={2}" , apiUrl.Contains( "?" ) ? "&" : "?" , p.Key, p.Value); } } ); var req = (HttpWebRequest)WebRequest.Create(apiUrl); req.Method = "POST" ; req.ContentType = "application/json" ; //Defalt if (!requestBody.IsNullOrEmpty()) { using (var postStream = new StreamWriter(req.GetRequestStream())) { postStream.Write(requestBody); } } if (headers != null ) { if (headers.Keys.Any(p => p.ToLower() == "content-type" )) req.ContentType = headers.SingleOrDefault(p => p.Key.ToLower() == "content-type" ).Value; if (headers.Keys.Any(p => p.ToLower() == "accept" )) req.Accept = headers.SingleOrDefault(p => p.Key.ToLower() == "accept" ).Value; } var response = (HttpWebResponse)req.GetResponse(); using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding( "UTF-8" ))) { resuleJson = reader.ReadToEnd(); } } } catch (Exception ex) { return default (T); } return JsonConvert.DeserializeObject<T>(resuleJson); } |
这样即可正确发送 Json 数据。
到此这篇关于C#通过HttpWebRequest发送带有JSON Body的POST请求实现的文章就介绍到这了,更多相关C# post请求 HttpWebRequest内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_21265915/article/details/98730675