Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build HTTP GET request with port number and parameters

I am trying to do a very simple thing, build an URL for a get request that contains a port number and some parameters, as it follows http://localhost:8080/read?date=whatever

I have tried several ways without success, it shouldn't be too difficult but i cannot come up with a solution.

I hope someone helps me, it would be greatly appreciated

Thanks in advance

like image 319
Fran Sevillano Avatar asked Feb 13 '11 15:02

Fran Sevillano


2 Answers

The previous answer was not to the question you actually asked. Try this:

import urllib

myPort = "8080"
myParameters = { "date" : "whatever", "another_parameters" : "more_whatever" }

myURL = "http://localhost:%s/read?%s" % (myPort, urllib.urlencode(myParameters)) 

Basically, urllib has a function to do what you want, called urlencode. Pass it a dictionary containing the parameter/parameter_value pairs you want, and it will make the proper parameters string you need after the '?' in your url.

like image 78
Michael Kent Avatar answered Nov 05 '22 16:11

Michael Kent


Here's a simple generic class that you can (re)use:

import urllib
class URL:
    def __init__(self, host, port=None, path=None, params=None):
        self.host = host
        self.port = port
        self.path = path
        self.params = params

    def __str__(self):
        url = "http://" + self.host
        if self.port is not None:
            url += ":" + self.port
        url += "/"
        if self.path is not None:
            url += self.path
        if self.params is not None:
            url += "?"
            url += urllib.urlencode(self.params)
        return url

So you could do:

url = URL("localhost", "8080", "read", {"date" : "whatever"})
print url
like image 22
Richard J Avatar answered Nov 05 '22 16:11

Richard J