Wednesday, September 3, 2014

How To: Send HTTP POST Request in Java using Apache HttpClient

This example code shows how you can send data (or parameters) to a URL using POST. This is the complete program source code.

The Apache HttpClient library simplifies handling HTTP requests. To use this library download the binaries with dependencies from http://hc.apache.org/ and add them to your project classpath.

HttpClient class is used to retrieve and send data. An instance of this class can be created with new DefaultHttpClient(). DefaultHttpClient is the standard HttpClient.

The HttpClient uses a HttpUriRequest to send and receive data. HttpPost is an important subclass of HttpUriRequest. The response of the HttpClient can be get as an InputStream.

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class PostDataExample {

    public static String postData(String postURL, String urlParameters) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(postURL);

            StringEntity strEntity = new StringEntity(urlParameters);
            httppost.setEntity(strEntity);
            httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
 
            // Execute HTTP Post Request
            HttpResponse response = client.execute(httppost);
         
            // Read response
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null){
                result.append(line);
            }
            in.close();
         
            return result.toString();
         
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        String params = "id=1432&name=Testing&locale=";
        System.out.println(postData("http://www.example.com/test.php", params));
    }

}


Feel free to comment if you have any questions about the code above.

Tuesday, September 2, 2014

How To: Download contents of a URL in Java using HTTPClient

This Java function can be used to download a webpage into a StringBuilder instance using the HTTPClient class. You have to import the necessary libraries.

public static String getURLContents(String url) {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    StringBuffer str = new StringBuffer();
 
    try {
        HttpResponse response = client.execute(request);
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
        String line = "";
        while ((line = reader.readLine()) != null){
            str.append(line);
        }
        in.close();
    } catch (Exception e) {return "";}
 
    return str.toString();
}


If you have any questions, feel free to comment below.

Monday, September 1, 2014

How To: Show Posts From Only Specific Categories on Your WordPress Homepage

Sometimes you'll need to show posts from only one category on your homepage. It's easy enough to do it. Following are the steps you need to follow:

Find Your Category ID

First you will have to find the ID of the category you want to show. When you're in the admin, hover over the edit link (or the title) for any of your categories and look at the address in your status-bar (that's the bar along the bottom of your browser window if you don't know about it), you should see the category ID at the end of the URL.

You can also use a plugin called Reveal IDs for this purpose.

Insert Code

Once you have your category ID, open your functions.php file and insert the following function code: (Appearances > Editor > Theme Functions – functions.php)

function my_home( $query ) {
  if ( $query->is_home() && $query->is_main_query() ) {
     $query->set( 'cat', '5');
  }
}
add_action( 'pre_get_posts', 'my_home' );


In this example above, the category ID I have used is 5.

If you would like to include more than one category, then just add another ID by inserting a comma and the ID number. For example, this will display posts from category 5 and 6:

$query->set( 'cat', '5, 6' );

You can also use get_cat_id() function for retrieving the category, like this:

$cat_id = get_cat_id('category name');
$query->set( 'cat', $cat_id );


And that's all. You should now see posts only from this category on your homepage.

Happy coding!