尝试运行发布请求并且即使传递数据也没有数据被发送?后端报告未发送任何帖子数据,并且我检查了它似乎没有发送?
我已经仔细检查了所有内容,但我不明白为什么? StackOverflow不断要求我提供更多描述,对不起冗长的解释。
var response = HttpFactory.PerformHttpWebRequest("http://localhost:8000/api/cache"
new Dictionary<string, string>()
{
{ "item", Username },
{ "name", Name },
{ "picture", Picture },
{ "additional_data", JsonConvert.SerializeObject(MetaData) },
}, "POST");
private static HttpResponse PerformHttpWebRequest(
string url,
IDictionary<string, string> data = default,
string method = "GET"
)
{
if (method == "GET" && data != null)
{
url += "?" + string.Join("&", data.Select((x) => x.Key + "=" + x.Value));
}
LAST_PROCESSED = url;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
if (data != null && method == "POST")
{
byte[] postData = Encoding.ASCII.GetBytes(string.Join("&", data.Select((x) => x.Key + "=" + x.Value)));
using (Stream stream = request.GetRequestStream())
{
stream.Write(postData, 0, postData.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
return new HttpResponse(url, response.StatusCode, reader.ReadToEnd());
}
}
catch (WebException we)
{
var response = (HttpWebResponse)we.Response;
if (response == null)
{
return new HttpResponse(url, default, default, we);
}
var reponseStream = new StreamReader(we.Response.GetResponseStream());
return new HttpResponse(url, response.StatusCode, reponseStream.ReadToEnd());
}
catch (Exception e)
{
return new HttpResponse(url, default, default, e);
}
}
答案 0 :(得分:0)
您正在设置request.ContentType = "application/json; charset=UTF-8";
,但实际上是在发布application/x-www-form-urlencoded
。
您可以尝试更改吗?