Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
3  
for (String s in parameters)? Is it supposed to compile? And don't swallow exceptions, report them. – PhiLho Jun 7 '11 at 18:19
2  
While System.err.println(e) isn't really swallowing an exception, it's not really reporting it properly either. If you must print somewhere instead of logging, at least use e.printStackTrace() – Alan Krueger Mar 19 '12 at 20:58
I don't think you want to modify the inside of the try block, as you've effectively prevented the finally block from releasing each connection you're attempting. – Alan Krueger Mar 19 '12 at 21:03

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.