HttpConnection Class
The HttpConnection class makes a HTTP connection to a given URI. You can use it to make GET and POST requests to other web services.
HTTPS calls are supported only for URIs that have standard security certificates.
When you call the execute method in HttpConnection, it executes the request, gets the response, and closes the connection. This means that a single object cannot be used multiple times. For multiple HTTP requests, instantiate multiple instances.
Note: Make sure that the URL is properly encoded when instantiating an HttpConnection object.
Constructor
You create an instance of HttpConnection using the new operator.
- Signature of the Method
HttpConnection con = new HttpConnection(int methodType, String URI)
- methodType
- Sets the HTTP method type:
- CONSTANTS.HTTP.METHOD.GET for HTTP GET requests
- CONSTANTS.HTTP.METHOD.POST for HTTP POST requests
- String URI
- URI to which to connect
Methods
addHeader
Adds a key-value pair to the request header.
- Signature of the Method
void addHeader(String key, String value)
- Parameters
- key
- The name of the key
- value
- The value of the key
- Return
- None
addParameter
Adds a parameter to an HTTP POST request. This methods throws an exception if it is called for an HTTP GET request.
- Signature of the Method
void addParameter(String key, String value)
- Parameters
- key
- The name of the key
- value
- The value of the key
- Return
- None
execute
Executes the request and returns a standard HTTP response such as "200 - OK" or "404 - not found".
- Signature of the Method
int execute()
- Parameters
- None
- Return
- Standard HTTP response
getResponse
Returns the response as a String.
- Signature of the Method
String getResponse()
- Parameters
- None
- Return
- The response from the service
encode
Returns a String encoded from s.
- Signature of the Method
String encode(String s)
- Parameters
-
- s
- The string to encode
- Return
- The encoded string
getResponseHeaders
This method will retrieve the headers from the HTTP Response from an external server. It is a map of String Header Name/Header Value pairs.
For example, if the Header Content-Length is equal to 10008, then "Content-Length" is the Header Name and "10008" is the Header Value.
This method is to be called after execute method of HttpConnection.
- Signature of the Method
- HashMap<String name, String value> getResponseHeaders()
- Parameters
- None
- Return
- A HashMap of Header Name/Header Value string pairs
HttpConnection Example
This example gets the result of a Google search for "IT Leaders".
<syntaxhighlight lang="java" enclose="div"> HttpConnection con = new HttpConnection(CONSTANT.HTTP.METHOD.GET,
"http://www.google.com/search?hl=en&q=IT+Leaders&btnG=Google+Search");
int code= con.execute(); String response = con.getResponse(); </syntaxhighlight >