38

I am trying to use the Python requests module to issue Http GET commands to access some REST based APIs. The urls are working fine on a RESTClient but when I use the same url in python, I get a connection error.

The code I am trying to execute is:

payload={"mac":new_mac,"token":token}
userloginurl="http://192.168.1.40:9119/uid"
r=requests.get(userloginurl,params=payload)
print(r.url)

If I test this url using RESTClient, I get a 200 OK status code in the response header along with some more fields. enter image description here But this is not working with python requests. The traceback of the error is shown below:

Traceback (most recent call last):
File "getAPids.py", line 34, in <module>
r=requests.get(userloginurl,params=payload)
  File "C:\Users\garvitab\python\lib\site-packages\requests\api.py", line 65, in
 get
return request('get', url, **kwargs)
File "C:\Users\garvitab\python\lib\site-packages\requests\api.py", line 49, in
request
response = session.request(method=method, url=url, **kwargs)
File "C:\Users\garvitab\python\lib\site-packages\requests\sessions.py", line 4
61, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\garvitab\python\lib\site-packages\requests\sessions.py", line 5
73, in send
r = adapter.send(request, **kwargs)
 File "C:\Users\garvitab\python\lib\site-packages\requests\adapters.py", line 4
15, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', BadStatusLine("''",
))

I looked up for the cause of the problem. Possibly, the response received is not formatted correctly. Is there a way to handle this problem?

Thanks in advance.

BajajG
  • 2,134
  • 2
  • 25
  • 32

4 Answers4

41

The problem was with the url. This connection was meant to be established over https and I was using http in the python script. Hence the issue.

BajajG
  • 2,134
  • 2
  • 25
  • 32
3

Have you actually checked, what gets send over the wire? I suppose you might have to convert your dictionary to a JSON string by yourself, or use the json= keyword instead of payload=. See http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers for details. This may do the trick:

import json
payload = json.dumps({"mac":new_mac,"token":token})
userloginurl = "http://192.168.1.40:9119/uid"
r = requests.get(userloginurl, data=payload)
print(r.url)
Michael
  • 7,316
  • 1
  • 37
  • 63
  • Thanks for replying back. I tried this approach but the error still persists. According to other SO questions on this topic, this is a problem of improperly formatted response generated by the server or an unknown status code generated in the response. I am still trying to figure out the exact cause of the error. – BajajG Feb 17 '15 at 10:09
  • One of the quickest ways to find out what's going wrong on unencrypted connections is to simply sniff your traffic using wireshark for both requests, and compare the difference. On encrypted traffic, enable debug output of the raw requests sent. – Michael Feb 17 '15 at 10:52
  • Thanks for the suggestion but the real problem was with the url. – BajajG Feb 17 '15 at 14:55
  • I had this error coming up because my api call used json in the body. I was using that data kwarg to feed the dictionary. (must have been the data was fed as form-data style) Changed it to json and the error resolved. thanks. – ThinkBonobo Jul 09 '15 at 02:01
1

I was getting the same error and spent hours on it. I found that you cannot call the flask server in a client using "Localhost". It has to be "127.0.0.1"

#server
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
   return 'Hello World'

if __name__ == '__main__':
   app.run(debug=True)

Now the client causing the error:

#client
import requests
x = requests.get('http://localhost:5000') # change it to 127.0.0.1
print(x.text)
cloud_IaaS
  • 91
  • 2
  • 6
  • OP doesn't used `localhost` or `flask` in his question. And in general this depends on your hosts config or how you started your local server. – Sven Eberth May 31 '21 at 13:16
0

In my case i was sending files of to large a size. I ended up streaming them and if they were still too large I decreased the size if there's and error:

this is sent to my own server and literally copy and pasted so you may not have _first or may have to change some things:

def upload_to_server(url, filedir, filename):
    print(f'uploading {k}')
    upload_file_path = os.path.join(filedir, filename)

    def read_in_chunks(file_object, chunk_size=524288):
        while True:
            data = file_object.read(chunk_size)
            if not data:
                break
            yield data

    trys = 5
    for i in range(trys):
        try:
            _first = 'true'
            with open(upload_file_path, 'rb') as f:
                for piece in read_in_chunks(f, chunk_size=int(524288 / (i + 1))):
                    r = requests.post(
                        url + '/upload/stream',
                        files={filename: piece)
                               },
                        headers={'first': _first})
                    # print('piece sent')
                    _first = 'false'
                    # print(r)
                    # print(r.text)
            break
        except ConnectionError as e:
            print(e)

    print(f'{k} was uploaded')
Daniel Olson
  • 73
  • 1
  • 3