2017-08-15 56 views
0

我试图发送POST原始请求到chromedriver服务器。使用套接字发送原始POST请求

这是我尝试启动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) 

输出:

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)"}}' 

错误的总结: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)) 

输出:

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}}' 

输出的摘要:json对象由chromedriver成功解析和new session创建

你,伙计们,有一个想法,为什么发送原始POST请求使用socket未按预期工作?

+0

那么,你在你的POST拼写错误的“内容”。 –

+0

Hi @JamesKPolk我修好了,对不起。尽管如此,它仍然表现得很好。 – CuriousGuy

+0

你可以记录什么'请求'实际上发送并重用它与套接字:https://stackoverflow.com/questions/10588644/how-can-i-see-the-entire-http-request-thats-being-sent-通过-我的Python应用程序 – Vovanrock2002

回答

2

有关于你的HTTP请求的几个问题:

  • HTTP请求的主体应该从头部通过\r\n\r\n分开。
  • 您需要Content-Length字段,否则远程主机不知道您的身体何时完成。
  • 在HTTP 1.1中,Host字段是强制性的。 (既然你收到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": {}}') 

要在视觉上更清晰,有效的HTTP请求看起来像

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

{"capabilities": {}, "desiredCapabilities": {}}