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

时间:2014-05-08 05:04:18

标签: 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: 

请帮我解决问题

1 个答案:

答案 0 :(得分:1)

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())