1.调用接口方法
@RestController
@RequestMapping("/admin/operationApiController")
public class OperationApiController {
@Autowired
private OperationApiDAO operationApiDAO;
String https ="https://localhost:8080/";
public ModelAndView startService(@Valid @ModelAttribute("x")String x, HttpServletRequest request,
HttpServletResponse response, ModelMap modelMap) throws Exception {
Gson gson =new Gson();
JsonParser parser =new JsonParser();
JsonObject jsonObject =(JsonObject)parser.parse(x);
RequestDTO requestDTO = gson.fromJson(jsonObject, RequestDTO.class);
String buttonType ="/admin/CallCrossDomain";
String resp = operationApiDAO.invokeRest(x,https + buttonType);
modelMap.addAttribute("successString",resp);
return new ModelAndView("/login/serviceShow");
}
}
public class OperationApiDAOImpl implements OperationApiDAO {
@Override
public String invokeRest(String json, String url) throws Exception {
String resp ="";
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest =new HttpPost(url);
postRequest.setHeader("Content-Type","application/json");
StringEntity stringEntity =new StringEntity(json);
postRequest.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(postRequest);
String responStr = EntityUtils.toString(response.getEntity(), "UTF-8");
if (response.getStatusLine().getStatusCode() != 200){
throw new Exception("Error:" + responStr);
}else {
resp =responStr;
}
return resp;
}
}
@Data
public class RequestDTO {
private Map<String,String> header;
private Map<String,Map<String,String>> body;
public String toString(){
StringBuffer json =new StringBuffer();
json.append("{");
for (String k:header.keySet()){
json.append(k + ":" + header.get(k) + "/n");
}
for (String k:body.keySet()){
json.append(k + "{");
Map<String,String> temp =body.get(k);
for (String key:temp.keySet()){
json.append(key + ":" + temp.get(key) +"\n");
}
json.append("}");
}
json.append("}");
return json.toString();
}
}
调用的接口 /admin/CallCrossDomain
@RequestMapping(value = "/admin/CallCrossDomain",method = RequestMethod.POST)
@ResponseBody
public String CallCrossDomain(@RequestBody RequestDTO requestDTO){
String command = requestDTO.getBody().get("data").get("command");
Runtime rt = Runtime.getRuntime();
String line="";
try {
Process p = rt.exec(command);
BufferedReader in =new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer stringBuffer =new StringBuffer();
String str="";
while ((str =in.readLine()) !=null){
line =stringBuffer.append(str).toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return line;
}