Sunday, November 8, 2015

How to send http request using python and how to send file in http request using python

We are here to discuss about how we can send request to http server and catch the response and display the output using Requests in Python.

For achieving this task we need package called "requests"

To install Requests, simply:  pip install requests
Sample program:
import requests
url = "http://192.168.6.1:8080/Service1/Request?"
r = requests.post(url, "login")
print (r.elapsed)    // time taken to complete the transaction
print (r.text)         //  Response that is given by the http request will be printed here 
print (r.status_code) // Status of the transaction i.e., if the transaction got success/fail 
Output:
0.0001
pass
success

Below is the program to send file(json/xml) over http request using Requests in Python:
import requests
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
url = "http://192.168.6.1:8080/Service2/Request1?"  #...requesting url
files =open('Request.json', 'rb')
files=files.read()
string=str(files.decode("utf-8"))
r = requests.post(url, string)
print (r.elapsed)
print (r.text)  
print (r.status_code)

Output:
0.0002
pass
success

In this case it depends as the result will be in plain text or even we can expect response in file. Then we need to read the file and then we need to print the response..

No comments:

Post a Comment