How can I send a POST request from a Servlet or JSP?

Luigi Viggiano

There's nothing in the servlet API that let you to use the POST method for submitting data to any URL; but your servlet can enstablish a URL connection to the php page, send the parameters you need as HTTP body and print out the response in its body.

See also the following FAQs:

I've written some code (two servlets: a Source and a Target) to test this scenario:


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class Source extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html";

    public void doGet(HttpServletRequest request, 
		      HttpServletResponse response) throws ServletException, 
		      IOException {
	response.setContentType(CONTENT_TYPE);

	URL		 url;
	URLConnection    urlConn;
	DataOutputStream cgiInput;

	// URL of target page script.
	url = new URL("http://localhost:8086/servlet/Target");
	urlConn = url.openConnection();

	urlConn.setDoInput(true);
	urlConn.setDoOutput(true);
	urlConn.setUseCaches(false);
	urlConn.setRequestProperty("Content-Type", 
				   "application/x-www-form-urlencoded");

	// Send POST output.
	cgiInput = new DataOutputStream(urlConn.getOutputStream());

	String content = "param1=" + URLEncoder.encode("first parameter") 
			 + "&param2=" 
			 + URLEncoder.encode("the second one...");

	cgiInput.writeBytes(content);
	cgiInput.flush();
	cgiInput.close();

	// reads the CGI response and print it inside the servlet content
	BufferedReader cgiOutput = 
	    new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
	PrintWriter    servletOutput = response.getWriter();        
	servletOutput.print("<html><body><h1>This is the Source Servlet</h1><p />");
	String line = null;
	while (null != (line = cgiOutput.readLine())){
	    servletOutput.println(line);
	}
	cgiOutput.close();
	servletOutput.print("</body></html>");
	servletOutput.close();
    }
}





import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class Target extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html";

    public void doPost(HttpServletRequest request,
		       HttpServletResponse response) throws ServletException,
		       IOException {
	response.setContentType(CONTENT_TYPE);
	PrintWriter out = response.getWriter();
	out.print("<h2>Target's output</h2><p /><pre><code>");

	Enumeration enum = request.getParameterNames();
	while (enum.hasMoreElements()){
	    String param = (String) enum.nextElement();
	    String value = request.getParameter(param);
	    out.println("param=" + param + " value=" + value);
	}
	out.print("</code></pre>");
    }
}

0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact