Python PUT error using urllib2

I am trying to do http using urllib2.

The server administrator said that I need to provide data in the following format: {"Type": "store", "data": ["9953"]}

My code looks like this:

url = 'https://url.com/polling/v1/5cb401c5-bded-40f8-84bb-6566cdeb3dbb/stores'
request = urllib2.Request(url, data='{\"type\":\"store\",\"data\":[\"9953\"]}')
request.add_header("Authorization", "Basic %s" % creds)
request.add_header("Content-type", "application/json")
request.add_header("Accept", "application/json")
print "Data: %s" % request.get_data()
print "Accept: %s" % request.get_header("Accept")
print "Content-Type: %s" % request.get_header("Content-type")
print "Authorization: %s" % request.get_header("Authorization")
try:
    result = urllib2.urlopen(request, data )
except urllib2.HTTPError as e:
    print e.read()
    exit()
data = json.loads(result.read())
print data

      

My output on startup:

Data: {"type":"store","data":["9953"]}
Accept: application/json
Content-Type: application/json
Authorization: Basic U1lTQ1RMOmFiYzEyMw==

      

This is exactly what I was told to send

But I am getting the following error:

BWEB000065: HTTP Status 400 - org.codehaus.jackson.JsonParseException: Unexpected end-of-input: expected close marker for ARRAY (from [Source: org.jboss.resteasy.core.interception.MessageBodyReaderContextImpl$InputStreamWrapper@695dd38d; line: 2, column: 15])

      

Any help would be appreciated.

+3


source to share


1 answer


Notice these two lines of code:

request = urllib2.Request(url, data='{\"type\":\"store\",\"data\":[\"9953\"]}')

result = urllib2.urlopen(request, data)

      

On the first line, you initialize the request by passing in the data

named parameter set to the JSON payload. It seems right.



However, the second line then goes through data

, overwriting the payload that you initialized on the first line. I suppose data

here is some kind of variable in the broader context of your program (not shown in the original question) and that this variable is data

set to some other value, possibly an invalid JSON payload.

If the payload on the first line is initialized correctly, then I suggest changing the second line as follows:

result = urllib2.urlopen(request)

      

+2


source







All Articles