PDF download Download Article PDF download Download Article

HTTP Post is part of a deprecated HTTP classes like org.apache.http and AndroidHttpClient as of Android 5.1. [1] Migrate your code to the HttpURLConnection classes which includes Posting functionality. HTTP Post is used in Java to request that a specific web server receive and store data submitted within a request form. The data is submitted and stored in name-value pairs. Examples of pairs include: email-your email address; username-your username; and password-your password.

Part 1
Part 1 of 2:

Creating a Try Block and HttpURLConnection Object

PDF download Download Article
  1. 1
    Add internet permissions to the Android Manifest. The Android Manifest is an XML file that provides important information to the Android system that determines device compatibility and access to features. In the “AndroidManifest.xml” file, enter the following line to provide internet access.
       <uses-permission 
       android:name= 
       "android.permission.INTERNET" 
       /> 
      
  2. 2
    Create a try block. In Java, a try statement is an exception handler that will prevent the program from crashing if it is not able to perform an action. Because this will require a connection to a network location, a try statement will catch an exception if it is not able to establish a connection. You can add this to a new Java method. [2]
       try 
       { 
       //enter statements that can cause exceptions 
       } 
      
    Advertisement
  3. 3
    Build HttpURLConnection and URL objects. Java is an Object-Oriented language. An object is comprised of states and behaviors which is an instance of a class. The HttpURLConnection object sends and receives data over the internet. In your code, begin your new method by creating a URL object and assign it a URL for the HttpURLConnection object to connect to. [3]
       URL 
       url 
       = 
       new 
       URL 
       ( 
        
       http 
       : 
       //exampleurl.com/”); 
       HttpURLConnection 
       client 
       = 
       ( 
       HttpURLConnection 
       ) 
       url 
       . 
       openConnection 
       (); 
      
    • For best practice, establish the URL and HttpURLConnection objects outside of the try block to make it easier to catch exceptions.
    •  URL 
       url 
       = 
       new 
       URL 
       ( 
        
       http 
       : 
       //exampleurl.com/”); 
       HttpURLConnection 
       client 
       = 
       null 
       ; 
       try 
       { 
       client 
       = 
       ( 
       HttpURLConnection 
       ) 
       url 
       . 
       openConnection 
       (); 
       } 
      
  4. Advertisement
Part 2
Part 2 of 2:

Posting the Output Request and Handling Exceptions

PDF download Download Article
  1. 1
    Set the request method to Post. In order to send information to the server, you must set the HttpURLConnection object’s type to post and set the output to true using setDoOutput(). Use the setRequestProperty() function to set a general request property which requires two elements, a key with a known request from the server and a value that’s contained within the corresponding key.
    • The setRequestProperty() function is used as the Accept-Encoding request header to disable automatic decompression.
       client 
       . 
       setRequestMethod 
       ( 
        
       POST 
        
       ); 
       client 
       . 
       setRequestProperty 
       ( 
        
       Key 
        
       , 
        
       Value 
        
       ); 
       client 
       . 
       setDoOutput 
       ( 
       true 
       ); 
      
  2. 2
    Output the stream to the server. You must request the output stream from the server in order to be able to write to the output stream, or post, then flush and close the stream when finished.
       OutputStream 
       outputPost 
       = 
       new 
       BufferedOutputStream 
       ( 
       client 
       . 
       getOutputStream 
       ()); 
       writeStream 
       ( 
       outputPost 
       ); 
       outputPost 
       . 
       flush 
       (); 
       outputPost 
       . 
       close 
       (); 
      
    • For performance reasons, it’s a good idea to let the server know how large in bytes the content will be. The best method is setFixedLengthStreamingMode(int) when the body length is known, [4] whereas setChunkedStreamingMode(int) is used if it’s length is not known. [5] Not using either of the previous methods causes the HttpURLConnection object to buffer the complete body in memory before being transmitted.
    •  client 
       . 
       setFixedLengthStreamingMode 
       ( 
       outputPost 
       . 
       getBytes 
       (). 
       length 
       ); 
       client 
       . 
       setChunkedStreamingMode 
       ( 
       0 
       ); 
      
  3. 3
    Catch any exceptions. After the try statement, use the catch block to check for an exception for input and output with IOException, catch a URL error with the MalformedURL exception and check if the URL does not provide a response in time with the SocketTimeoutException.
       catch 
       ( 
       MalformedURLException 
       error 
       ) 
       { 
       //Handles an incorrectly entered URL 
       } 
       catch 
       ( 
       SocketTimeoutException 
       error 
       ) 
       { 
       //Handles URL access timeout. 
       } 
       catch 
       ( 
       IOException 
       error 
       ) 
       { 
       //Handles input and output errors 
       } 
      
  4. 4
    Disconnect from the URL. After you are finished with your URL connection, you will need to disconnect from the URL. Be sure to check that you are connected to a URL before attempting to disconnect.
       finally 
       { 
       if 
       ( 
       client 
       != 
       null 
       ) 
       // Make sure the connection is not null. 
       client 
       . 
       disconnect 
       (); 
       } 
      
  5. Advertisement


Community Q&A

Search
Add New Question
  • Question
    How do I resolve the method 'writeStream(java.io.OutputStream)'?
    Community Answer
    This method seems to be just a sample of what you should do in this point. You need then to do your own implementation to write data to the OutputStream. You can find a simple samples on internet explaining how to write different types of data to an OutputStream.
  • Question
    Why do we need to include the android.permission.INTERNET line in the Android Manifest?
    Community Answer
    The Android Manifest file presents the Android system with essential information about the app and is required for every app in its root directory. The INTERNET permission grants access to the API that opens the device's network sockets.
  • Question
    I'm receiving errors that the symbol cannot be resolved for the URL and HttpURLConnection objects. What packages am I supposed to import?
    Community Answer
    Android Studio can be set to automatically import packages once the symbols are references or pasted into the code. You can also manually add in the packages by typing in and without the book ended arrow symbols. To set Android Studio to automatically import packages, Windows and Linux users must click on File>Settings>Edti>General>Auto Import>Java and Mac users must click on Android Studio>Preferences. Change "Insert imports on paste" to all and mark "Add unambiguous imports on the fly" then save your changes.
Ask a Question
      Advertisement

      Tips

      Submit a Tip
      All tip submissions are carefully reviewed before being published
      Thanks for submitting a tip for review!

      Things You'll Need

      • Java IDE
      • Android development tools (SDK, emulator, etc.)
      • Android developer's phone or other Android powered device (optional for testing)
      • Internet connection (for testing)

      Expert Interview

      Thanks for reading our article! If you’d like to learn more about dealing with mobile devices, check out our in-depth interview with Jessica Andzouana .

      About This Article

      Article Summary X

      1. Add internet permissions to the Android Manifest.
      2. Create a try block.
      3. Build HttpURLConnection and URL objects.
      4. Set the output to post to the server.

      Did this summary help you?
      Thanks to all authors for creating a page that has been read 413,953 times.

      Reader Success Stories

      • Sudarshan Mondal

        Jul 22, 2016

        "I was confused where to use post request. This article solved my problem."
      Share your story

      Is this article up to date?

      Advertisement