I am trying to convert a HTTP POST into Python and am not sure how to go about doing this.
I have the HTTP Request:
POST vision/v1/ocr?language=unk&detectOrientation =true
Content-Type: application/json
Host: api.projectoxford.ai
Content-Length: 95
Ocp-Apim-Subscription-Key: ••••••••••••••••••••••••••••••••
{ "Url": "exampleurl.com"}
As well as the URL request and need help on whether or not I am doing this correctly.
import urllib.parse
import urllib.request
url = "urlrequest.com"
values = {"Url":
https://exampleurl.com}
data = url.lib.parse.urlencode(values)
data = data.encode('utf-8')
req = urllib.request.Request(url, data)
with urllib.request.urlopen(req) as response:
the_page = response.read()
I am getting an HTTTPError:
HTTP Error 400: Bad Request.
1 Answer 1
You need to send JSON with additional header entries:
url = "http://api.projectoxford.ai/vision/v1/ocr?language=unk&detectOrientation=true"
data = json.dumps({'Url': 'exampleurl.com'}).encode('utf-8')
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '••••••••••••••••••••••••••••••••',
}
req = urllib.request.Request(url, data, headers)
with urllib.request.urlopen(req) as response:
the_page = response.read()
answered Oct 11, 2015 at 7:40
Daniel
42.8k4 gold badges57 silver badges82 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
BearBonesHacker
What does the json.dumps() do? I am getting "TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str."
lang-py
reqis undefined. Show correct code.dataafter encoding it. Please at least provide us with code that is free from syntax errors so we can determine if not usingdatacould be the issue.