Java using PostMethod multiple times I found a example of Java PostMethod here.

But I want to post several times by using for loop. I made it like this.


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;

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

public class PostMethodExample {

  public static void main(String args[]) {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");

    BufferedReader br = null;

    PostMethod method = new PostMethod("http://search.yahoo.com/search");
    method.addParameter("p", "\"java2s\"");

    try{
            String[] parameters = { "Google", "Yahoo", "MSN" };

            for (String s in parameters){
                int returnCode = client.executeMethod(method);
                method.addParameter("p", s);
                if(returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                    System.err.println("The Post method is not implemented by this URI");
                    // still consume the response body
                    method.getResponseBodyAsString();
                } else {
                    br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
                    String readLine;
                    while(((readLine = br.readLine()) != null)) {
                        System.err.println(readLine);
                    }
                }
                method.releaseConnection();
                method = new PostMethod("http://search.yahoo.com/search");
            }
    } catch (Exception e) {
      System.err.println(e);
    } finally {
      method.releaseConnection();
      if(br != null) try { br.close(); } catch (Exception fe) {}
    }
  }
}


I modified code just inside of try block. I don't think this is the best way. Help me to improve this code.
Avoid catching all exceptions

Do not use catch (Exception e) as this will also catch NullPointerException, ArrayIndexOutOfBoundsException and a whole lot of other ones. Only catch the Exceptions you need to catch, such as IOException. It is said that one should be specific in throws clause, but that applies for catch as well.

And as stated in the comments to your question, System.err.println(e) does not give full information about the exception. If you don't have a logger system nearby that can handle exceptions completely, at least use e.printStackTrace();. It is however recommended that you should handle and exception, and not only report it. For example by displaying a more accurate error message to the user.

Also, I would say that your line if(br != null) try { br.close(); } catch (Exception fe) {} should be on multiple lines. Even if it increases line count, it improves readability.

if (br != null) {
    try {
       br.close();
    }
    catch (Exception fe) {
    }
}