Last active
          July 12, 2024 03:11 
        
      - 
      
- 
        Save abitrolly/7cee9d2054a9bff715b86f0016e58e72 to your computer and use it in GitHub Desktop. 
    POST JSON with Python3 urllib
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # Public domain | |
| from urllib import request | |
| def post_data(url, data, headers={'Content-Type':'application/json'}): | |
| """ | |
| POST data string to `url`, return page and headers | |
| """ | |
| # if data is not in bytes, convert to it to utf-8 bytes | |
| bindata = data if type(data) == bytes else data.encode('utf-8') | |
| # need Request to pass headers | |
| req = request.Request(url, bindata, headers) | |
| resp = request.urlopen(req) | |
| return resp.read(), resp.getheaders() | |
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment