Simple URL GET/POST function in Python

前端 未结 5 1635
旧时难觅i
旧时难觅i 2020-11-28 18:52

I can\'t seem to Google it, but I want a function that does this:

Accept 3 arguments (or more, whatever):

  • URL
  • a dictionary of params
5条回答
  •  情深已故
    2020-11-28 19:28

    I know you asked for GET and POST but I will provide CRUD since others may need this just in case: (this was tested in Python 3.7)

    #!/usr/bin/env python3
    import http.client
    import json
    
    print("\n GET example")
    conn = http.client.HTTPSConnection("httpbin.org")
    conn.request("GET", "/get")
    response = conn.getresponse()
    data = response.read().decode('utf-8')
    print(response.status, response.reason)
    print(data)
    
    
    print("\n POST example")
    conn = http.client.HTTPSConnection('httpbin.org')
    headers = {'Content-type': 'application/json'}
    post_body = {'text': 'testing post'}
    json_data = json.dumps(post_body)
    conn.request('POST', '/post', json_data, headers)
    response = conn.getresponse()
    print(response.read().decode())
    print(response.status, response.reason)
    
    
    print("\n PUT example ")
    conn = http.client.HTTPSConnection('httpbin.org')
    headers = {'Content-type': 'application/json'}
    post_body ={'text': 'testing put'}
    json_data = json.dumps(post_body)
    conn.request('PUT', '/put', json_data, headers)
    response = conn.getresponse()
    print(response.read().decode(), response.reason)
    print(response.status, response.reason)
    
    
    print("\n delete example")
    conn = http.client.HTTPSConnection('httpbin.org')
    headers = {'Content-type': 'application/json'}
    post_body ={'text': 'testing delete'}
    json_data = json.dumps(post_body)
    conn.request('DELETE', '/delete', json_data, headers)
    response = conn.getresponse()
    print(response.read().decode(), response.reason)
    print(response.status, response.reason)
    

提交回复
热议问题