HTTP telnet POST/GAE 服务器问题(简单内容)

0 投票
1 回答
1249 浏览
提问于 2025-04-16 21:03

我正在玩弄HTTP传输,试图让一些东西正常工作。我有一个GAE服务器,我很确定它运行得很好,因为我用浏览器访问时可以正常显示,不过我还是把Python代码贴在这里:

import sys
print 'Content-Type: text/html'
print ''
print '<pre>'
number = -1
data = sys.stdin.read()
try:
    number = int(data[data.find('=')+1:])
except:
    number = -1
print 'If your number was', number, ', then you are awesome!!!'
print '</pre>'

我刚在学习HTTP的POST和GET以及响应的过程,但这是我在终端上做的事情:

$ telnet localhost 8080
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET http://localhost:8080/?number=28 HTTP/1.0

HTTP/1.0 200 Good to go
Server: Development/1.0
Date: Thu, 07 Jul 2011 21:29:28 GMT
Content-Type: text/html
Cache-Control: no-cache
Expires: Fri, 01 Jan 1990 00:00:00 GMT
Content-Length: 61

<pre>
If your number was -1 , then you are awesome!!!
</pre>
Connection closed by foreign host.

我这里用的是GET,因为我花了大约40分钟试图让telnet的POST工作,但都没有成功 :(

如果有人能帮我让这个GET和/或POST正常工作,我将非常感激。谢谢大家提前的帮助!!!!

1 个回答

2

在使用 GET 请求时,请求的主体里不会有任何数据,所以 sys.stdin.read() 这个方法肯定会失败。相反,你可以查看环境变量,特别是 os.environ['QUERY_STRING']

另外,你的请求格式有点奇怪。请求的第二部分不应该包含网址的协议、主机或端口,它应该像这样:

GET /?number=28 HTTP/1.0

你需要在一个单独的 Host: 头部中指定主机;服务器会自己判断协议。

在使用 POST 请求时,大多数服务器不会读取超过 Content-Length 头部指定的数据量。如果你没有提供这个头部,服务器可能会认为数据量是零字节。服务器可能会尝试读取在内容长度指定的点之后的字节,把它当作在持久连接中的下一个请求,如果这个请求不是有效的请求,服务器就会关闭连接。所以基本上:

POST / HTTP/1.0
Host: localhost: 8080
Content-Length: 2
Content-Type: text/plain

28

但是你为什么要在 telnet 中测试这个呢?试试 curl 吧?

$ curl -vs -d'28' -H'Content-Type: text/plain' http://localhost:8004/
* About to connect() to localhost port 8004 (#0)
*   Trying ::1... Connection refused
*   Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8004 (#0)
> POST / HTTP/1.1
> User-Agent: curl/7.20.1 (x86_64-redhat-linux-gnu) libcurl/7.20.1 NSS/3.12.6.2 zlib/1.2.3 libidn/1.16 libssh2/1.2.4
> Host: localhost:8004
> Accept: */*
> Content-Type: text/plain
> Content-Length: 2
> 
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Thu, 07 Jul 2011 22:09:17 GMT
< Server: WSGIServer/0.1 Python/2.6.4
< Content-Type: text/html; charset=UTF-8
< Content-Length: 45
< 
* Closing connection #0
{'body': '28', 'method': 'POST', 'query': []}

或者更好的是,用 Python 来做:

>>> import httplib
>>> headers = {"Content-type": "text/plain",
...            "Accept": "text/plain"}
>>> 
>>> conn = httplib.HTTPConnection("localhost:8004")
>>> conn.request("POST", "/", "28", headers)
>>> response = conn.getresponse()
>>> print response.read()
{'body': '28', 'method': 'POST', 'query': []}
>>> 

撰写回答