【发布时间】:2019-05-29 06:16:23
【问题描述】:
我想向“https://sslecal2.forexprostools.com/ajax.php”发出 Post 请求。所以有我的代码:
string URI = "https://sslecal2.forexprostools.com/ajax.php";
string requestBody = String.Format("{{\"dateFrom\": \"{0}\", \"dateTo\": \"{1}\", \"timeZone\": {2}, \"action\": \"{3}\"}}",
"2018-12-24", "2018-12-24", 18, "filter"); //json format
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URI); //make request
request.Method = "POST";
request.UserAgent = "";
request.Headers.Add("X-Requested-With", "XMLHttpRequest");
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(requestBody); //write your request payload
}
WebResponse response = request.GetResponse();
string jsonData = String.Empty;
using (var reader = new StreamReader(response.GetResponseStream()))
{
jsonData = reader.ReadToEnd();
}
response.Close();
我在字符串“ string requestBody = String.Format("{{\"dateFrom\"..." ”中的“requestBody”中做了一些不正确的事情,因为我得到了 200 和空的 html 答案。
我在 postman 中附加了相同请求的屏幕,并带有 html 代码作为答案。邮递员中的这个请求处理得很好。
【问题讨论】:
-
尝试设置用户代理。
-
您的邮递员版本使用的是
x-www-form-urlencoded,它不是 JSON。 (要使用 JSON,您将使用“原始”作为正文,并制作您的Content-Typeapplication/json。)我首先将邮递员更改为使用 JSON 来查看是否有效。 (所以你有一个苹果对苹果的比较)如果没有,你就会坚持使用x-www-form-urlencoded。你应该可以用谷歌来看看如何在 C# 中做到这一点。 -
@Neijwiert 尝试过
request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko";- 其余相同 -
@KirkWoll 谢谢,这是一个有趣的建议,因为当我将邮递员切换到 raw 和
{"dateFrom": "2018-12-24","dateTo": "2018-12-24","timeZone": 18,"action":"filter"}时,我得到了相同的结果:200 和空 html 的答案。 -
@mr_blond 是的,那么你就被 Reniuz 概述的 urlencoded 方法所困。
标签: c# post httpwebrequest postman