Fran Sevillano
Fran Sevillano

Reputation: 8163

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

Upvotes: 10

Views: 21677

Answers (2)

Richard J
Richard J

Reputation: 7313

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

Upvotes: 1

Michael Kent
Michael Kent

Reputation: 1734

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.

Upvotes: 12

Related Questions