Induction
CCHttpClient is an interface for HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests while handling cookies, authentication, connection management, and other features. Thread safety of HTTP clients depends on the implementation and configuration of the specific client.
Concepts
The general usage of CCHttpClient consists of just 6 steps:
-
Create an instance of CCHttpClient.
-
Create an instance of one of the methods (setUrl for example). The URL to connect to is passed in to the the method constructor.
-
Tell CCHttpClient to execute the method.
-
Read the response.
-
Release the connection.
-
Deal with the response.
How To Use
Instantiating HttpClient
The no argument constructor for CCHttpClient provides a good set of defaults for most situations so that is what we’ll use.
Creating a url
The various methods defined by the HTTP specification correspond to the various classes in CCHttpClient.
We will be using the Get method which is a simple method that simply takes a URL and gets the document the URL points to.
GET
The following is an example an HTTP Get request via CCHttpClient.
POST
The following will send a post request to the URL “http://www.httpbin.org/post” .
Read the Response
It is vital that the response body is always read regardless of the status returned by the server. There are three ways to do this:
Call getRequestData() This will return a raw data containing the data in the response body.
Release the Connection
This is a crucial step to keep things flowing. We must tell CCHttpClient that we are done with the connection and that it can now be reused. Without doing this CCHttpClient will wait indefinitely for a connection to free up so that it can be reused.
Deal with the Response
We’ve now completed our interaction with CCHttpClient and can just concentrate on doing what we need to do with the data. In our case, we’ll just print it out to the console.
It’s worth noting that if you were retrieving the response as a stream and processing it as it is read, this step would actually be combined with reading the connection, and when you’d finished processing all the data, you’d then close the input stream and release the connection.
Android
Note that if you environment is Android do not forget adding permissions on your app’s Manifest: