Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

How to use HttpURLConnection POST data to web server?

902241Mar 1 2012 — edited Mar 7 2012
Hi. I've searched the web after this but hasn't found anything that worked for me.

Here you can see my code. My intention is to post data to the second <form> in the URL but unfortunatelly I still get the original URL content. My intention is to get the result of posting the data to the url.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class POSTRequester {

	public static void bombearURL ( String urlString, Par... parametros) {
		
		try {
    	    // Construct data
    	    String data = "";
    	    for ( Par par : parametros ) {
    	    	if ( data.length() > 1 ) data += "&";
    	    	data += URLEncoder.encode(par.param, "UTF-8") + "=" + URLEncoder.encode(par.value, "UTF-8");
    	    }

    	    // Connect
    	    URL url = new URL(urlString);
    	    URLConnection conn = url.openConnection();
    	    
    	    // Send data
    	    conn.setDoOutput(true);
    	    conn.setDoInput(true); //
    	    
    	    // No caching, we want the real thing.
    	    conn.setUseCaches (false);
    	    // Specify the content type.
    	    conn.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded");   	    
    	    
    	    
    	    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    	    wr.write(data);
    	    wr.flush();

    	    // Get the response
    	    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    	    String line;
    	    while ((line = rd.readLine()) != null) {
    	        // Process line...
    	    	System.out.println(line);
    	    }
    	    wr.close();
    	    rd.close();
    	} catch (Exception e) {
    	}
		
		
	}
	
    public static void main(String[] args)  {
    	
    	bombearURL ("http://www.buscacep.correios.com.br/servicos/dnec/menuAction.do?Metodo=menuFaixaCep", 
    			new Par("UF", "SC"), 
    			new Par("Localidade", "Florianopolis") 
    	);
    	
    	
    }
    
}

class Par {
	
	String param;
	String value;
	
	public Par(String param, String value) {
		super();
		this.param = param;
		this.value = value;
	}
	
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 4 2012
Added on Mar 1 2012
35 comments
4,433 views