在JSP中执行cURL命令

时间:2013-05-29 13:20:21

标签: jsp servlets

如何在JSP中执行以下cURL命令,

$ curl -d lang=fr -d badge=0 http://www.redissever.com/subscriber/J8lHY4X1XkU

如果你用一些code.thanks

解释它会很有帮助

1 个答案:

答案 0 :(得分:2)

您可以使用Runtime.getRuntime().exec()从JSP scriptlet执行任何命令。

<%
Process p=Runtime.getRuntime().exec("..."); 
p.waitFor(); 
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream())); 
String line=reader.readLine(); 
while(line!=null) 
{ 
   out.println(line); 
   line=reader.readLine(); 
} 
%>

但是,如果您可以在纯Java中执行此操作,则不会执行外部命令,例如使用HttpUrlConnection

<%
URL url = new URL("...");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line=reader.readLine(); 
while(line!=null) 
{ 
   out.println(line); 
   line=reader.readLine(); 
}
%>

对于POST请求,您需要这样的内容:

connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes ("lang=fr&badge=0");
wr.flush ();
wr.close ();