0

This works fine, I can get data returned:

r = urllib2.Request("http://myServer.com:12345/myAction")
data = json.dumps(q) #q is a python dict
r.add_data(data)
r=urllib2.urlopen(r)

But doing the same with requests package fails:

r=requests.get("http://myServer.com:12345/myAction", data=q)
r.text #This will return a message that says method is not allowed.

It works if I make it a post request: r=requests.post("http://myServer.com:12345/myAction", data=json.dumps(q))

But why?

user1008636
  • 2,989
  • 11
  • 31
  • 45

2 Answers2

0

Set up a session

import session

session = requests.Session()
r = session.get("http://myServer.com:12345/myAction", data=q)
print r.content (<- or could us r.raw)
Attila Kis
  • 521
  • 2
  • 13
0

According to the urllib2.urlopen documentation:

the HTTP request will be a POST instead of a GET when the data parameter is provided.

This way, r=urllib2.urlopen(r) is also making a POST request. That is why your requests.get does not work, but requests.post does.

awesoon
  • 32,469
  • 11
  • 74
  • 99
  • Does that mean the server was set up to only receive POST requests? – user1008636 Feb 02 '18 at 14:49
  • Yes. Seems like this endpoint does not accept `GET` requests. Maybe it can receive also `PATCH`, `DELETE` or other request methods. So I am not sure that it is accepts `POST` methods *only*, the more correct statement is that this endpoint does not accept `GET` – awesoon Feb 02 '18 at 14:51
  • Why does the urllib2.urlopen force the request to be POST when data parameter is provided? Can't you have a http server that serves you data based on a request, without modifying anything on the server? Isn't that a classic GET request? – user1008636 Feb 02 '18 at 16:39
  • GET request does not have a body, it only accepts query parameters – awesoon Feb 02 '18 at 16:45
  • what is the difference between body and parameters – user1008636 Feb 02 '18 at 17:36
  • Parameters are part of url. Request body is a part of request. You may find the differences in the docs or in the questions like this: https://stackoverflow.com/questions/28039709/what-is-difference-between-requestbody-and-requestparam – awesoon Feb 04 '18 at 09:40