在JSP中执行cURL命令

问题描述 投票:1回答:1

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

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

如果您用一些代码解释会很有帮助。谢谢

jsp servlets
1个回答
3
投票

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

<%
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();
BufferedReader 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 ();    
© www.soinside.com 2019 - 2024. All rights reserved.