HTTP telnet POST / GAE服务器问题(SIMPLE STUFF)

时间:2011-07-07 21:32:33

标签: python http google-app-engine telnet

我正在玩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 vs Response流程,但这是我在终端上做的事情:

$ 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 个答案:

答案 0 :(得分:2)

使用GET时,请求正文中不会出现任何数据,因此sys.stdin.read()必然会失败。相反,您可能希望查看环境,特别是os.environ['QUERY_STRING']

你有点奇怪的是,你没有使用正确的请求格式。请求的第二部分不应包括url方案,主机或端口,它应该如下所示:

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 -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': []}
>>>