【发布时间】:2018-10-25 15:04:14
【问题描述】:
我是 JSON 和 C# 的新手,正在尝试 POST 请求并读取响应。
我正在正确编写内容类型,我尝试发送到服务器的 url 也是正确的。可能我的代码不正确,我将不胜感激。
以下是我的代码,但我不断收到 400 错误请求。
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
public class Server
{
public void ServerStart()
{
try{
string webAddr="https://localhost:61000/users/login";
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"userName\" : \"laborel\", \"userPassword\" : \"dGVzdG5ldFBDMSEu\" }";
streamWriter.Write(json);
streamWriter.Flush();
}
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (StreamReader streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
byte[] responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
}catch(WebException ex){
Console.WriteLine(ex.Message);
System.Windows.Forms.MessageBox.Show(string.Format ("Exception Occurred: {0}",ex.Message));
}
}
}
一件事byte[] responseText = streamReader.ReadToEnd(); 不对,我不知道应该在哪里下注responseText
有人可以告诉我如何创建一个函数,它接受网址和 json 字符串作为输入并返回响应文本
【问题讨论】:
-
获取
ex.Message的内部消息并将其打印到您的日志中,它会告诉您它的json是否无效,或者是什么交易。我会说,如果这是休息,您可能需要一个带有授权令牌的标头,但这可能是一些小事。 -
它还在问题中说 404 错误,我认为这不是发现错误,而是问题正文中的错误代码 400,这似乎是错误请求的正确错误