【问题标题】:send the HTTP request python发送 HTTP 请求 python
【发布时间】:2019-11-14 07:01:45
【问题描述】:

当我发送 HTTP 请求和服务器响应时,我收到类似这样的错误

"收到 b'HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=UTF-8\r\nX-Content-Type-Options: ...."

另外,当它接收成功时,我们如何将响应分成两部分:

>The part before the \r\n\r\n sequence - the HEADER
>The part after the \r\n\r\n sequence - the DATA. 
>And Save the DATA to disk as a binary file
# Split URL into "host", "path", and "filename" variables.
# http://www.google.com/images/srpr/logo3w.png
#  * host=www.google.com
#  * path=/images/srpr
#  * file=logo3w.png

request = "GET "+path+filename +"/ HTTP/1.1" + "\nHost: " + host +"\nConnection: close\r\n\r\n"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, port))

bytes_sent = s.send(send_request)

data = s.recv(64*1024)

print('Received', repr(data))

s.close()


【问题讨论】:

  • 如果问题是:如何在字符串上拆分数据,请执行 data.split("\r\n") 但除非您想了解 http,否则请使用 requests 库或其他更高级别的抽象为您处理此问题
  • 对于我目前的作业,我必须这样做

标签: python http


【解决方案1】:

您的代码中似乎有流氓/

request = "GET "+path+filename +"**/** HTTP/1.1" + "\nHost: " + host +"\nConnection: close\r\n\r\n"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

以下内容可让我获取图像。

import socket

filename='logo3w.png'
host='www.google.com'
path='/images/srpr/'
request = "GET "+ path + filename +" HTTP/1.1" + "\nHost: " + host +"\nConnection: close\r\n\r\n"
print (request)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((host, 80))

bytes_sent = s.send(request.encode())

data = s.recv(64*1024)

print('Received', repr(data))

s.close()

关于如何进一步拆分数据的问题,@Macattack 在 cmets 中提到的 data.split 应该适合您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-02
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2011-08-21
    相关资源
    最近更新 更多