C#Json Post抛出404错误的请求错误

时间:2018-10-25 15:04:15

标签: c# json post request

我是JSON和C#的新手,正在尝试POST请求并读取响应。

我正确编写了Content Type,我尝试发送到服务器的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();一件事是不对的,我不确定应该在哪个地方响应response

有人可以指出我如何创建一个函数,该函数接受网址和json字符串作为输入并返回响应文本

1 个答案:

答案 0 :(得分:0)

遵循以下操作string responseText = streamReader.ReadToEnd();