为什么python请求工作但C#请求不起作用?

时间:2016-09-07 07:08:06

标签: c# python postman

首先,我尝试在PostMan工具中发布脚本。

{"AO":"ECHO"}

工作正常。然后我在C#中写这个请求,但它不起作用。 我在Python中再次编写请求,并且运行良好。 但我的项目是在Microsoft C#中。我不想在C#中运行脚本Python。

==== Python =========

import httplib
import json
import sys

data = '{"AO":"ECHO"}'
headers = {"Content-Type": "application/json", "Connection": "Keep-Alive" }
conn = httplib.HTTPConnection("http://10.10.10.1",1040)
conn.request("POST", "/guardian", data, headers)
response = conn.getresponse()

print response.status, response.reason
print response.msg

==== C#============

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://10.10.10.1:1040/guardian");

            httpWebRequest.Method = "POST";

            httpWebRequest.ContentType = "application/json";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {

                string json = "{\"AO\":\"ECHO\"}";

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();

                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                    Console.WriteLine(result);
                }
            }

我尝试输入“ContentLength”,但它仍然超时异常。 我尝试使用RestSharp,它不是超时但返回null。 任何人请帮忙...

            var client = new RestClient("http://10.10.10.1:1040/guardian");
            var request = new RestRequest();

            request.Method = Method.POST;
            request.AddHeader("Content-Type", "application/json");
            request.Parameters.Clear();
            request.RequestFormat = DataFormat.Json;
            request.AddBody(new { AO = "ECHO" });

            var response = client.Execute(request);
            var content = response.Content;

请帮帮我, 我不明白为什么它在python中工作正常。 但为什么它不在C#中工作。 我尝试在C#中找到许多请求,但是在超时时出现错误异常。

1 个答案:

答案 0 :(得分:0)

Python会自动添加Content-Length http标头。 https://docs.python.org/2/library/httplib.html#httpconnection-objects

我认为您可能必须在C#中手动设置此标头。

httpWebRequest.ContentLength = json.length;

根据服务器的不同,您可能还需要设置UserAgent。

httpWebRequest.UserAgent=".NET Framework Test Client";
相关问题