使用套接字发送原始POST请求

Cur*_*Guy 1 python sockets http webdriver

我正在尝试将原始POST请求发送到chromedriver服务器。

这是我尝试启动的内容new session

import socket

s = socket.socket(
    socket.AF_INET, socket.SOCK_STREAM)

s.connect(("127.0.0.1", 9515))

s.send(b'POST /session HTTP/1.1\r\nContent-Type:application/json\r\n{"capabilities": {}, "desiredCapabilities": {}}\r\n\r\n')
response = s.recv(4096)
print(response)
Run Code Online (Sandbox Code Playgroud)

输出:

b'HTTP/1.1 200 OK\r\nContent-Length:270\r\nContent-Type:application/json; charset=utf-8\r\nConnection:close\r\n\r\n{"sessionId":"b26166c2aac022566917db20260500bb","status":33,"value":{"message":"session not created exception: Missing or invalid capabilities\\n  (Driver info: chromedriver=2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8),platform=Linux 4.4.0-91-generic x86_64)"}}'
Run Code Online (Sandbox Code Playgroud)

错误摘要:json我发送的对象未正确解析

当我使用同一json对象但通过requests库发送它时,一切正常:

import requests

params = {
        'capabilities': {},
        'desiredCapabilities': {}
    }


headers = {'Content-type': 'application/json'}

URL = "http://127.0.0.1:9515"

r = requests.post(URL + "/session", json=params)

print("Status: " + str(r.status_code))
print("Body: " + str(r.content))
Run Code Online (Sandbox Code Playgroud)

输出:

Status: 200
Body: b'{"sessionId":"e03189a25d099125a541f3044cb0ee42","status":0,"value":{"acceptSslCerts":true,"applicationCacheEnabled":false,"browserConnectionEnabled":false,"browserName":"chrome","chrome":{"chromedriverVersion":"2.31.488763 (092de99f48a300323ecf8c2a4e2e7cab51de5ba8)","userDataDir":"/tmp/.org.chromium.Chromium.LBeQkw"},"cssSelectorsEnabled":true,"databaseEnabled":false,"handlesAlerts":true,"hasTouchScreen":false,"javascriptEnabled":true,"locationContextEnabled":true,"mobileEmulationEnabled":false,"nativeEvents":true,"networkConnectionEnabled":false,"pageLoadStrategy":"normal","platform":"Linux","rotatable":false,"setWindowRect":true,"takesHeapSnapshot":true,"takesScreenshot":true,"unexpectedAlertBehaviour":"","version":"60.0.3112.90","webStorageEnabled":true}}'
Run Code Online (Sandbox Code Playgroud)

输出摘要:json对象已成功由解析chromedrivernew session创建

伙计们,您是否知道为什么使用发送原始POST请求socket无法正常工作?

sau*_*ger 6

有关您的HTTP请求的几个问题:

  • HTTP请求的主体应与头分开\r\n\r\n
  • 您需要该Content-Length字段,否则远程主机不知道您的身体何时完成。
  • Host字段在HTTP 1.1中是必填项。(由于收到200您的第一个请求,您的服务器可能没有坚持。)

我通过使用以下示例使您的示例可以工作(使用apache网络服务器):

s.send(b'POST /session HTTP/1.1\r\nHost: 127.0.0.1:9515\r\nContent-Type: application/json\r\nContent-Length: 47\r\n\r\n{"capabilities": {}, "desiredCapabilities": {}}')
Run Code Online (Sandbox Code Playgroud)

为了更加直观,有效的HTTP请求看起来像

POST /session HTTP/1.1
Host: 127.0.0.1:9515
Content-Type: application/json
Content-Length: 47

{"capabilities": {}, "desiredCapabilities": {}}
Run Code Online (Sandbox Code Playgroud)