c# - 从 C# 客户端向 python 服务器发送 http POST 请求时出错

标签 c# python http post cherrypy

我是客户端服务器编程的初学者(特别是我没有 python 服务器端编程的经验)。我正在尝试将一些数据发送到使用 cherry.py HTTP 框架的 python 服务器。以下代码显示了服务器实现。

import cherrypy
from cherrypy import request

class test:
    @cherrypy.expose
    def index(self):
        print request.params['port']
        return "Done";


if __name__ == "__main__":
    cherrypy.config.update( {'server.socket_host':"0.0.0.0", 'server.socket_port':8181 } )
    cherrypy.quickstart(test())  

我需要使用 C# 客户端发送 POST 类型请求。这是我用来发送数据的方法。

    private void applicationOn()
    {

        using (var client = new WebClient())
        {
            var values = new NameValueCollection();
            values["port"] = "hello";

            var ret = client.UploadValues("http://localhost:8181/", "POST", values);
            MessageBox.Show(Encoding.ASCII.GetString(ret));
        }
    }

尽管此客户端程序在 PHP 上运行良好,但在 python 上却无法正常运行。当我尝试发送请求时,它给了我这个错误

“远程服务器返回错误:(400) 错误请求。” 这是堆栈跟踪。

    System.Net.WebException was unhandled
      HResult=-2146233079
      Message=The remote server returned an error: (400) Bad Request.
      Source=System
      StackTrace:
           at System.Net.WebClient.UploadValues(Uri address, String method, NameValueCollection data)
           at System.Net.WebClient.UploadValues(String address, String method, NameValueCollection data)
           at HTTP_Client.Form1.applicationOn() in c:\Users\pusalk\Documents\Visual Studio 2012\Projects\HTTP Client\HTTP Client\Form1.cs:line 125
           at HTTP_Client.Form1.button1_Click(Object sender, EventArgs e) in c:\Users\pusalk\Documents\Visual Studio 2012\Projects\HTTP Client\HTTP Client\Form1.cs:line 29
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
           at System.Windows.Forms.Button.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.Run(Form mainForm)
           at HTTP_Client.Program.Main() in c:\Users\pusalk\Documents\Visual Studio 2012\Projects\HTTP Client\HTTP Client\Program.cs:line 19
           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException: 

请帮我解决一下问题

最佳答案

CherryPy 处理程序不需要任何参数,试试这个:

import cherrypy
from cherrypy import request

class test:
    @cherrypy.expose
    def index(self, **params):
        # all the request parametes goes into the params dictionary.
        # in case that no port is defined return None
        print params.get('port', None) 
        return "Done";


if __name__ == "__main__":
    cherrypy.config.update( {'server.socket_host':"0.0.0.0",
                             'server.socket_port':8181 })
    cherrypy.quickstart(test())  

关于c# - 从 C# 客户端向 python 服务器发送 http POST 请求时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23533113/

相关文章:

c# - 在 Mono C# Readline 中捕获 Control+key

c# - 如何在 PowerShell 中创建具有行为(方法)的真实对象?

c#:检查哪个项目正在调用类库

c# - 无法使用 Cosmos 3.3 sdk 使用 CreateItemAsync 写入我的容器

json - 我如何修复 "Error Domain=NSCocoaErrorDomain Code=3840 "无值 ."UserInfo={NSDebugDescription=No value.}"

python - Box2D 不适用于 Python

python - 使用贪心Python算法解决背包问题

python - 仅递归调用internal_dep中存在的键值或跳过跳过列表中存在的键值

http - 无法下载附件文件 - cURL 工作正常 - 缺少 header ?

javascript - 请求从 Postman 工作,但在命令行中从 Axios 重置