Android Development: Sending POST Requests with Parameters

After I had published a tutorial about how to request RESTful web services in a native Android App, I have been asked by some of you about how to also send data to web services. That is why I wanted to quickly demonstrate how you would achieve sending POST requests containing parameters to a web server.


Sending POST Requests

Though it is actually not required by any specification, RESTful web services usually expect a POST request when data shall be updated on the server. In order to tell our connection to submit a POST request, we need to add few lines to the method which is opening the HTTP connection:

URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = 
	(HttpURLConnection) urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", 
	"application/x-www-form-urlencoded");

Adding Request Parameters

Now we need to write our parameters, if any, to the request output stream.

urlConnection.setFixedLengthStreamingMode(
	postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();

Whereas postParameters is the query string, such as “param1=value1&param2=value2”.

Create Query Strings

For the sake of a nicer API, I always offer a little helper method which creates correctly encoded query strings.

private static final char PARAMETER_DELIMITER = '&';
private static final char PARAMETER_EQUALS_CHAR = '=';
public static Sring createQueryStringForParameters(Map<String, String> parameters) {
	StringBuilder parametersAsQueryString = new StringBuilder();
	if (parameters != null) {
		boolean firstParameter = true;
		
		for (String parameterName : parameters.keySet()) {
			if (!firstParameter) {
				parametersAsQueryString.append(PARAMETER_DELIMITER);
			} 
			
			parametersAsQueryString.append(parameterName)
				.append(PARAMETER_EQUALS_CHAR)
				.append(URLEncoder.encode(
					parameters.get(parameterName)));
			
			firstParameter = false;
		}
	}
	return parametersAsQueryString;
}

GET and POST combined

Combining the snippets, we can adapt the code from the previous tutorial in a way that the method can send both GET and POST requests.

public static String requestUrl(String url, String postParameters) 
	throws YourServiceRequestException {
	if (Log.isLoggable(LOGGER_TAG, Log.INFO)) {
		Log.i(LOGGER_TAG, "Requesting service: " + url);
	}
	
	disableConnectionReuseIfNecessary();

	HttpURLConnection urlConnection = null;
	try {
		// create connection
		URL urlToRequest = new URL(url);
		urlConnection = (HttpURLConnection) urlToRequest.openConnection();
		urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
		urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);
		
		// handle POST parameters
		if (postParameters != null) {
			
			if (Log.isLoggable(LOGGER_TAG, Log.INFO)) {
				Log.i(LOGGER_TAG, "POST parameters: " + postParameters);
			}
			
			urlConnection.setDoOutput(true);
			urlConnection.setRequestMethod("POST");
			urlConnection.setFixedLengthStreamingMode(
				postParameters.getBytes().length);
			urlConnection.setRequestProperty("Content-Type", 
				"application/x-www-form-urlencoded");
			
			//send the POST out
			PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
			out.print(postParameters);
			out.close();
		}
		
		// handle issues
		int statusCode = urlConnection.getResponseCode();
		if (statusCode != HttpURLConnection.HTTP_OK) {
			// throw some exception
		}
		
		// read output (only for GET)
		if (postParameters != null) {
			return null;
		} else {
			InputStream in = 
				new BufferedInputStream(urlConnection.getInputStream());
			return getResponseText(in);
		}
		
		
	} catch (MalformedURLException e) {
		// handle invalid URL
	} catch (SocketTimeoutException e) {
		// hadle timeout	
	} catch (IOException e) {
		// handle I/0
	} finally {
		if (urlConnection != null) {
			urlConnection.disconnect();
		}
	}
	
	return null;
}
Advertisements

Tags: , ,

13 responses to “Android Development: Sending POST Requests with Parameters”

  1. Suzsain says :

    will you plz provide full source code with java classes as I am new to Web service?

  2. Ben says :

    I am new to android development as well. Could you please contact me and help me get started with this?

  3. Ayham says :

    Thank you man ,, seems perfect (Y)

  4. Kiran says :

    Gud article, precise and very helpful 🙂

    C’mon, Please do write more articles on Android. !

  5. amr elghadban says :

    it throw error
    if remove this line
    // urlConnection.setFixedLengthStreamingMode(postParameters
    // .getBytes().length);
    it works fine with me

    • Ingo.Hofmann says :

      What kind of error do you get? It still works fine for me. Just note that you must not write more into the request body than what is here “postParameters”, otherwise you will get an exception.

  6. anchal says :

    please provide full source code for it…it will be very helpful

  7. J V Babu says :

    How to send data using urlConnection ??

  8. ozshabat says :

    an awsome guide!

    Unfortunately, I keep getting the 200 response code on the post request and not 302.

    any idea why?

    • Ingo.Hofmann says :

      Thanks for your comment. 200 is the right status code (= OK). 302 means that the provided URL points to a redirection. My provided code will work on 200 and fail for any other response. It might not be the best behavior, so feel free to make a better issue handling, which I haven’t really covered in this tutorial.

  9. Desiree Gonzalez says :

    Hello Ingo, I have a connection code but with deprecated methods (HttpPost httpPost and HttpClient), could you tell me how can I fix this code please?

    private void consultaBdx(List params, String url){
    try {
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params));
    try{
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse resp;
    resp = httpClient.execute(httpPost);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: