UTF-8 encoding at post values with HttpClient

It took me a while to find out how, so I believe it will be useful for you too.

HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://urlhere.com");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("name1", "utfvalue1"));
nameValuePairs.add(new BasicNameValuePair("name2", "utfvalue2"));
UrlEncodedFormEntity formEntity = null;
try {
	formEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
} catch (UnsupportedEncodingException e2) {
	e2.printStackTrace();
}
if (formEntity != null)
	httpPost.setEntity(formEntity);

...
Share

Copy the content of an input stream to an output stream

How to copy the content of an input stream to an output stream

/**
* Copy the content of the input stream into the output stream, using a temporary
* byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
*
* @throws IOException If any error occurs during the copy.
*/
private static final int IO_BUFFER_SIZE = 4 * 1024;

private static void copy(InputStream in, OutputStream out) throws IOException {
   byte[] b = new byte[IO_BUFFER_SIZE];
   int read;
   while ((read = in.read(b)) != -1) {
      out.write(b, 0, read);
   }
}
Share

Closing streams like a boss

This is one of my favorite tips and I also consider it a good practice.
How to close any java input or output Stream.

/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
   try {
      stream.close();
   } catch (IOException e) {
   Log.e("IO", "Could not close stream", e);
}
} 
Share

How to sort RSS by date

So, if you’ve got one or more RSS feeds and you want to sort them according to the pubdate, do this:

Collections.sort(myFeedsList, new Comparator<RssItemModel>() {

            @Override
            public int compare(RssItemModel lhs, RssItemModel rhs) {
                SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                try {
                    Date date1 = formatter.parse(rhs.getPubDate());
                    Date date2 = formatter.parse(lhs.getPubDate());
                    return date1.compareTo(date2);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
Share