如何发送和接收原始JSON?

时间:2014-10-15 19:48:52

标签: c# json

我需要一些帮助来确定这个方向。我只需要程序在给定的IP和端口向服务器发送一个固定的原始简单JSON格式的消息,然后它需要监听给定端口上的响应,然后将原始响应写出到控制台。

我发现了一些关于做JSON http请求的主题,但我认为我没有走上正确的道路。这是我试图改编的代码。

public static void send_json()
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://10.211.55.5:7752");
    request.ContentType = "application/json; charset=utf-8";
    request.Accept = "application/json";
    request.Method = "POST";
    using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
    {
        writer.Write("{\"request\": \"get_menu\", \"checksum\": \"\", \"table_state\": {\"table_id\": \"1\", \"waiter_id\": \"1001\"}}");
    }

    WebResponse response = request.GetResponse();
    Stream stream = response.GetResponseStream();
    string json = "";

    using (StreamReader reader = new StreamReader(stream))
    {
        while (!reader.EndOfStream)
        {
            json += reader.ReadLine();
        }
        Console.Write(json);
    }
}

1 个答案:

答案 0 :(得分:0)

以下代码最终正常运行!谢谢你指点我正确的方向!

private void pos_test_button_Click(object sender, EventArgs e)
    {
        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        clientSocket.Connect("127.0.0.1", 7777);

        string get_menu_request = "{\"request\": \"get_menu\"}";
        NetworkStream serverStream = clientSocket.GetStream();
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(get_menu_request);
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();

        byte[] inStream = new byte[10025];
        serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
        string _returndata = System.Text.Encoding.ASCII.GetString(inStream);

        test_log_box.AppendText("\r\n\r\nPOS Connection Test: " + "\r\n" + _returndata);
    }