为了账号安全,请及时绑定邮箱和手机立即绑定

有什么方法可以通过给定的请求格式文本来初始化 HTTP 请求吗?

有什么方法可以通过给定的请求格式文本来初始化 HTTP 请求吗?

不负相思意 2023-06-27 13:41:30
我有一个 GET 请求格式的文本:GET /40x.jpg HTTP/1.1\r\n\Host: ns.pb.cachecn.net\r\n\Connection: keep-alive\r\n\Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n\User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1636.2 Safari/537.36\r\n\Accept-Encoding: gzip,deflate,sdch\r\n\Accept-Language: zh-CN,zh;q=0.8\r\n\\r\n"我们知道Python中有三种模块方式来创建HTTP请求:urllib2/urllibhttplib/urllibRequests但是是否可以通过导入给定的文本来创建 HTTP 请求?我的意思是使用 a string = the GET request text,并使用这个变量string来创建 HTTP 请求。不要使用很多步骤,因为区分request header,很复杂request body。
查看完整描述

3 回答

?
阿晨1998

TA贡献2037条经验 获得超6个赞

库 ( urllib2/urllib, httplib/urllib, Requests) 被封装以方便高级使用。


如果你想发送格式化的HTTP请求文本,你应该考虑Python套接字库。


有一个套接字示例:


import socket


get_str = 'GET %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36\r\nAccept: */*\r\n\r\n'%("/", "www.example.com")


def get(hostname, port):

    sock = socket.socket()

    sock.connect((hostname, port))


    b_str = get_str.encode("utf-8")

    sock.send(b_str)


    response = b''

    temp = sock.recv(4096)

    while temp:

        temp = sock.recv(4096)

        response += temp


    return response.decode(encoding="utf-8")


res = get(hostname="www.example.com", port=80)

print(res)


查看完整回答
反对 回复 2023-06-27
?
达令说

TA贡献1821条经验 获得超6个赞

如果您真的非常愿意,您可以欺骗http.client.HTTPSConnection(或http.client.HTTPConnection对于普通的 HTTP 连接)做您想做的事情。这是Python 3代码;在Python 2中应该可以使用不同的导入和常规字符串而不是字节。


import http.client


# Requesting https://api.ipify.org as a test

client = http.client.HTTPSConnection('api.ipify.org')

# Send raw HTTP. Note that the docs specifically tell you not to do this

# before the headers are sent.

client.send(b'GET / HTTP/1.1\r\nHost: api.ipify.org\r\n\r\n')

# Trick the connection into thinking a request has been sent. We are

# manipulating the name-mangled __state attribute of the connection,

# which is very, very ugly.

client._HTTPConnection__state = 'Request-sent'

response = client.getresponse()

# should print the response body as bytes, in this case e.g. b'123.10.10.123'

print(response.read())

请注意,我不建议您这样做;这是一个非常令人讨厌的黑客行为。尽管您明确表示不想解析原始请求字符串,但这绝对是正确的做法。


查看完整回答
反对 回复 2023-06-27
?
白衣非少年

TA贡献1155条经验 获得超0个赞

您可以将该字符串写入连接到 HTTP 服务器端口的套接字对象,但这是发出请求的相当困难的方法。我建议使用 requests 包。它真的很简单又方便。



查看完整回答
反对 回复 2023-06-27
  • 3 回答
  • 0 关注
  • 130 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信