1

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.
3
  • req is undefined. Show correct code. Commented Oct 11, 2015 at 7:25
  • Your code has syntax errors, nor are you actually using data after encoding it. Please at least provide us with code that is free from syntax errors so we can determine if not using data could be the issue. Commented Oct 11, 2015 at 7:26
  • I'm sorry. I missed a line of code. It is corrected to show my code now. Commented Oct 11, 2015 at 7:38

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.