HTTP or HTTPS Post in Android using HTTPURLConnection

I’m starting to dive deep into Android world. The first step is usually the hardest. I’m starting to grasp how the Android environment operates. The best way for me to learn is by reading, and actually doing it. So, I started to build a room reservation app using an web service API built by my co-worker. Calling this API requires HTTP POST call from Android. This is where it gets interesting. I tried scouring the web for hours, and all the example I found did not work! I finally looked into android documentation, which is really where I should started first. It seems so simple. I could do it in 10 seconds in c#. However during my trial, all the post parameters are not recognized by the API, which is written using PHP. I’ll describe some of the mistake I made.

//import these on your header

import java.io.IOException;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Scanner;

//do this wherever you are wanting to POST
URL url;
HttpURLConnection conn;

try{
//if you are using https, make sure to import java.net.HttpsURLConnection
url=new URL(“http://somesite/somefile.php”);

//you need to encode ONLY the values of the parameters
String param=”param1=” + URLEncoder.encode(“value1″,”UTF-8”)+
“&param2=”+URLEncoder.encode(“value2″,”UTF-8”)+
“&param3=”+URLEncoder.encode(“value3″,”UTF-8”);

conn=(HttpURLConnection)url.openConnection();
//set the output to true, indicating you are outputting(uploading) POST data
conn.setDoOutput(true);
//once you set the output to true, you don’t really need to set the request method to post, but I’m doing it anyway
conn.setRequestMethod(“POST”);

//Android documentation suggested that you set the length of the data you are sending to the server, BUT
// do NOT specify this length in the header by using conn.setRequestProperty(“Content-Length”, length);
//use this instead.
conn.setFixedLengthStreamingMode(param.getBytes().length);
conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);
//send the POST out
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.close();

//build the string to store the response text from the server
String response= “”;

//start listening to the stream
Scanner inStream = new Scanner(conn.getInputStream());

//process the stream and store it in StringBuilder
while(inStream.hasNextLine())
response+=(inStream.nextLine());

}
//catch some error
catch(MalformedURLException ex){
Toast.makeText(MyActivity.this, ex.toString(), 1 ).show();
}
// and some more
catch(IOException ex){

Toast.makeText(MyActivity.this, ex.toString(), 1 ).show();
}

That’s it. Whatever output you receive from the URL you are calling would be stored in response string.

20 thoughts on “HTTP or HTTPS Post in Android using HTTPURLConnection

  1. For those encountered “AppName” has stopped working, and the error is address from the line of “PrintWriter out = new PrintWriter(conn.getOutputStream());”
    Put this code on the first line of onCreate()

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    ——————————————–
    And if your code has working but you received invalid characters from the target url, put some characters inside “param” String.

    EX.

    String param= “param1=”+URLEncoder.encode(“value1″,”UTF-8”) +
    “&param2=”+URLEncoder.encode(“value2″,”UTF-8”) +
    “&param3=”+URLEncoder.encode(“value3″,”UTF-8”);

    Hope it helps. Btw I am using ASP.NET for my web.

  2. You are a hero! Been stuck with a problem where by the web service was responding with HTTP 400 for a week! Setting a fixed length content size seemed to work.

  3. The article is issued at 2011 and now it’s 2015. But it solved my problem after around 5 days searching and testing different suggestions. Nice and simple. Many thanks.
    However, in my case, i put the above code in an asyncTask to avoid main thread problems.
    Thanks again.

  4. Thanks for the post.

    I am running on Android 4.1. In my case, EOFException is thrown by conn.getInputStream().
    conn.getContentLength() is 0. Any idea why?

    Also, param1, param2 in your code should match the name or the id field in the HTML source? Thanks for your help.

  5. Hi,

    I know I’m really late but I gotta try since this code is perfect for me but I’m getting an error.
    Everything checks out but one thing, when I use this code I get:

    “loginUrl cannot be resolved”

    You possibly know why?

    BR

  6. I savour, lead to I discovered exactly what I
    was having a look for. You have ended my 4 day long hunt!

    God Bless you man. Have a nice day. Bye

  7. Hello Budi, My name is Parnit Sainion. I am trying to create an app that logins into an SSO authenticated website (with user login credentials) to get JSON data. I have tried HTTPClient but that does not work. I wanted to know the code posted above can help, and If it will, where do I add the Username/password? Any help will be appreciated

  8. I’ve been looking everywhere to find this. I didn’t have to url-encode the parameters but the rest was perfect for me! Thank you!

    1. what android sdk version are you using?
      try adding
      conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);
      after
      conn.setFixedLengthStreamingMode(param.getBytes().length);

      1. It should be url

        Try this code

        —————————————

        import java.io.IOException;
        import java.io.PrintWriter;
        import java.io.UnsupportedEncodingException;
        import java.net.HttpURLConnection;
        import java.net.MalformedURLException;
        import java.net.ProtocolException;
        import java.net.URL;
        import java.net.URLEncoder;
        import java.util.Scanner;

        public class Poster {

        //do this wherever you are wanting to POST
        URL url;
        HttpURLConnection conn;

        {
        //if you are using https, make sure to import java.net.HttpsURLConnection
        try {
        url=new URL(“http://example.com/test.php”);
        } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }

        //you need to encode ONLY the values of the parameters
        String param = null;
        try {
        param = “number=” + URLEncoder.encode(“919971707954″,”UTF-8”);
        } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }

        try {
        conn=(HttpURLConnection)url.openConnection();
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        //set the output to true, indicating you are outputting(uploading) POST data
        conn.setDoOutput(true);
        //once you set the output to true, you don’t really need to set the request method to post, but I’m doing it anyway
        try {
        conn.setRequestMethod(“POST”);
        } catch (ProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }

        //Android documentation suggested that you set the length of the data you are sending to the server, BUT
        // do NOT specify this length in the header by using conn.setRequestProperty(“Content-Length”, length);
        //use this instead.
        conn.setFixedLengthStreamingMode(param.getBytes().length);
        conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);
        //send the POST out
        PrintWriter out = null;
        try {
        out = new PrintWriter(conn.getOutputStream());
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
        out.print(param);
        out.close();

        //build the string to store the response text from the server
        String response= “”;

        //start listening to the stream
        Scanner inStream = null;
        try {
        inStream = new Scanner(conn.getInputStream());
        } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }

        //process the stream and store it in StringBuilder
        while(inStream.hasNextLine())
        response+=(inStream.nextLine());

        }
        //catch some error

        }

Leave a Reply

Your email address will not be published. Required fields are marked *

*