MABeatty1978
MABeatty1978

Reputation: 115

Python failure to PUT using urllib2

I'm trying to do an http put using urllib2.

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

My code is as follows:

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 when I run this is:

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

Which is exactly what I was told to send

But I'm 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.

Upvotes: 3

Views: 251

Answers (1)

Chris Nauroth
Chris Nauroth

Reputation: 9844

Notice these 2 lines of code:

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

result = urllib2.urlopen(request, data)

In the first line, you are initializing the request by passing the data named parameter set to the JSON payload. This appears to be correct.

However, then the second line passes in data, overwriting the payload that you initialized in the first line. I assume that data here is some variable in the larger context of your program (not shown in the original question), and that this data variable is set to some different value, perhaps an invalid JSON payload.

If the payload in the first line is initialized correctly, then I suggest changing the second line to this:

result = urllib2.urlopen(request)

Upvotes: 2

Related Questions