I have a REST API which is intended to return XML as response. The API is built using PHP. However, internally it communicates with a JSP servlet running on a Tomcat server installed on another machine inside my network. What is the ideal way to invoke the servlet and pass on the response to the end user ? In this particular case, there is no processing that has to be done in the PHP layer on getting the response from the servlet. Currently, I am using cURL to do http post from php and getting the entire response from the servlet and returning that to the user. However, the xml response might be large and this might cause memory issues with PHP. So I need to implement the same by streaming the response.
The current implementation code is given below :
PHP:
public function curlPost($url,$data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
return $server_output;
}
--
$url = "http://base_url_to_invoke_servlet/";
$data = "param_1=".$params[0]."¶m_2=".$params[1];
$result = curlPost($url,$data);
Header ( 'Content-type: text/xml' );
echo $result;
Servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
public class MyAPIServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGetPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGetPost(request, response);
}
private void doGetPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getQueryString());
APIRequestManager apiReqMgr = new APIRequestManager();
XMLStreamWriter xmlWriter = null;
XMLOutputFactory factory = XMLOutputFactory.newInstance();
ServletOutputStream outputStream = response.getOutputStream();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/xml");
try {
xmlWriter = factory.createXMLStreamWriter(outputStream);
apiReqMgr.executeRequest(request,xmlWriter);
} catch (XMLStreamException e) {
e.printStackTrace();
}
finally{
try {
if(xmlWriter != null){
xmlWriter.flush();
xmlWriter.close();
}
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
}
}