【问题标题】:Why python request working but C# request not working?为什么 python 请求有效但 C# 请求无效?
【发布时间】:2017-01-14 18:11:23
【问题描述】:

首先,我尝试在 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# 中查找许多请求,但出现超时错误异常。

【问题讨论】:

  • 你的问题是不是类似here
  • 亲爱的@Shankfk,我的问题不一样。它在我的网络服务器上进行测试。执行此操作仅需 3 秒。并且它在 python 脚本中运行良好,如上所述。但是在 C# 中它根本不起作用,它返回错误异常超时。但是我尝试更改超时。
  • Python 和 C# 使用相同的编码吗?
  • 我是 python 新手,这让我坚持使用它
  • 你能发布服务器代码吗?还是让服务器可以从 Internet 访问并发布 URL?

标签: c# python postman


【解决方案1】:

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";

【讨论】:

  • 嗨 Veener,它仍然出现同样的错误。似乎不适合这种方式。
  • 此时我将使用 fiddler 或 Wireshark 来检查 http 流量,并比较两种语言发送到服务器的请求和响应。
猜你喜欢
  • 2014-09-18
  • 1970-01-01
  • 2018-08-03
  • 2023-03-14
  • 2021-11-18
  • 1970-01-01
  • 2023-03-19
  • 2020-09-27
  • 2018-10-27
相关资源
最近更新 更多