使用 Twisted python 从 C# 程序向服务器发布消息时出错
我使用 C# .NET 4.0 将消息发布到服务器的方法
private String postHTTP(String url)
{
String result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
string postData = "Data has Posted";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
**request.ContentType = "application/x-www-form-urlencoded";**
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
txtWebServerStatus.Text = ((HttpWebResponse)response).StatusDescription;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
我的服务器代码提供了一个表单来键入和打印您在表单中键入的内容
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.error import NoResource
import cgi
class DynamicPage(Resource):
def render_GET(self, request):
return '<html><body><form method="POST"><input name="the-field" type="text" /></form></body></html>'
def render_POST(self, request):
return '<html><body>You submitted: %s</body></html>' % (cgi.escape(request.args["the-field"][0]),)
root = Resource()
dynamic = DynamicPage()
root.putChild("fool", dynamic)
factory = Site(root)
reactor.listenTCP(7777, factory)
reactor.run()
post 方法出错: 在行 WebResponse response = request.GetResponse();
远程服务器返回错误:(500) 内部服务器错误。
当我使用 post 方法时,服务器上出现错误:
C:\Users\sepdau>C:\Python27\python.exe E:\server.py
Unhandled Error Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1349, in dataReceived finishCallback(data[contentLength:])
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1563, in _finishRequestBodyself.allContentReceived()
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1618, in allContentReceived req.requestReceived(command, path, version)
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 773, in request Received self.process()
--- <exception caught here> ---
File "C:\Python27\lib\site-packages\twisted\web\server.py", line 132, in process
self.render(resrc)
File "C:\Python27\lib\site-packages\twisted\web\server.py", line 167, in render
body = resrc.render(self)
File "C:\Python27\lib\site-packages\twisted\web\resource.py", line 216, in render
return m(request)
**File "E:\server.py", line 25, in render_POST
return '<html><body>You submitted: %s</body></html>' % (cgi.escape(request.a
rgs["the-field"][0]),)
exceptions.KeyError: 'the-field'**
我认为服务器或 ContentType 上有错误,我使用的不正确。 你能帮助我吗。 感谢您的提前。
My Method to post a message to server using C# .NET 4.0
private String postHTTP(String url)
{
String result = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
string postData = "Data has Posted";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
**request.ContentType = "application/x-www-form-urlencoded";**
request.Credentials = System.Net.CredentialCache.DefaultCredentials;
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
txtWebServerStatus.Text = ((HttpWebResponse)response).StatusDescription;
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
return responseFromServer;
}
my server code to provide a form to type and print what you type in form
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web.error import NoResource
import cgi
class DynamicPage(Resource):
def render_GET(self, request):
return '<html><body><form method="POST"><input name="the-field" type="text" /></form></body></html>'
def render_POST(self, request):
return '<html><body>You submitted: %s</body></html>' % (cgi.escape(request.args["the-field"][0]),)
root = Resource()
dynamic = DynamicPage()
root.putChild("fool", dynamic)
factory = Site(root)
reactor.listenTCP(7777, factory)
reactor.run()
Error on post method:
in line WebResponse response = request.GetResponse();
The remote server returned an error: (500) Internal Server Error.
When I using post method have error on server:
C:\Users\sepdau>C:\Python27\python.exe E:\server.py
Unhandled Error Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1349, in dataReceived finishCallback(data[contentLength:])
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1563, in _finishRequestBodyself.allContentReceived()
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 1618, in allContentReceived req.requestReceived(command, path, version)
File "C:\Python27\lib\site-packages\twisted\web\http.py", line 773, in request Received self.process()
--- <exception caught here> ---
File "C:\Python27\lib\site-packages\twisted\web\server.py", line 132, in process
self.render(resrc)
File "C:\Python27\lib\site-packages\twisted\web\server.py", line 167, in render
body = resrc.render(self)
File "C:\Python27\lib\site-packages\twisted\web\resource.py", line 216, in render
return m(request)
**File "E:\server.py", line 25, in render_POST
return '<html><body>You submitted: %s</body></html>' % (cgi.escape(request.a
rgs["the-field"][0]),)
exceptions.KeyError: 'the-field'**
I think error on Server or ContentType I use no correct.
Can you help me.
Thank for advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以您遇到的问题是:
这是因为您的客户正在发布:
该发布数据中没有表单字段。您可能想做两件事。
首先,让您的服务器更强大地抵御不良输入。它已经有些稳健了:错误的输入会生成 500,但服务器会继续运行并处理未来的请求。不过,您可能希望生成一个更有用的错误页面来帮助客户找出他们做错了什么。因此,尝试处理 KeyError:
现在您的客户端应该收到 200 响应,即使它不断提交表单数据而没有服务器正在查找的表单字段。
接下来,修复您的客户端以提交包含正确表单字段的发布数据。尝试使用如下字符串:
您可以使用 urllib.urlencode 在 Python 中生成此字符串,例如:
So the problem you're hitting is:
This is because your client is posting:
There are no form fields in that post data. There are two things you probably want to do.
First, make your server more robust against bad input. It's already somewhat robust: bad input generates a 500, but the server continues to operate and process future requests. You might want to generate a more useful error page to help clients figure out what they're doing wrong, though. So, try handling the KeyError:
Now your client should get a 200 response, even if it keeps submitting form data without the form field the server is looking for.
Next, fix your client to submit post data that includes the correct form fields. Try a string like:
You can generate this in Python using
urllib.urlencode
, eg: