1. Standardize the processing of returned results
public interface INetResult<T> {
void getNetData(T data) ;
}
Copy the code
2. Encapsulate asynchronous request callback methods
/** * Created by gaowenFeng on 2017/8/23. ** * Created by GaowenFeng on 2017/8/23 CallbackString implements FutureCallback<HttpResponse>{/** * */ private INetResult<String> netResult; @param Response */ public void completed(HttpResponse Response) {String content =""; try { content = EntityUtils.toString(response.getEntity(), Constants.ENCONDING); } catch (IOException e) { e.printStackTrace(); } netResult.getNetData(content); } @param e */ public void failed(Exception e) {e.printStackTrace(); } /** * cancel callback method */ public voidcancelled() {}}Copy the code
3. Encapsulate Http request methods
Public class HttpUtil {/** * executePost request * @param request * @param callBack */ protected static void executePost(HttpPost) Request, CallbackString callBack) {/ / perform the requested object CloseableHttpAsyncClient httpclient. = HttpAsyncClients createDefault (); httpclient.start(); httpclient.execute(request,callBack); try { httpclient.close(); } catch (IOException ignore) {}} /** * Encapsulates the JSON object * @param Param JSON object * @returnHttpPost Available StringEntity */ protected static StringEntity parseEntity(String param){StringEntity entity = new StringEntity(param, Constants.ENCONDING); entity.setContentEncoding(Constants.ENCONDING); entity.setContentType(Constants.CONTENT_TYPE);returnentity; }}Copy the code
4. The Service class that performs the specific Http request
Public class HttpClient extends HttpUtil{// Extends HttpUtil to send HTTP requests /** * To execute requests to create workSpace * @param workSpace @param callBack */ public static void createWorkSpace(String port,WorkspaceConfig workSpace, CallbackString callBack){ HttpPost request = new HttpPost(CheCommands.getWorkSpaceUrl(port)); // Post request, need to pass in the request URL String entity = json. toJSONString(workSpace); // convert entity into JSON object request.setEntity(parseEntity(entity)); executePost(request,callBack); }}Copy the code
5. Test
public static void mian(String[] args){
HttpClient.createWorkSpace(port, workSpaceConfig, new CallbackString(data -> {
System.out.println(data);
}));
}
Copy the code
6.Java executes remote Linux commands
7. Perform the configuration required for remote Linux
Zip Download link Run the following command
mvn install:install-file -DgroupId=com.ganymed.ssh2 "-DartifactId=ganymed-ssh2-build" "-Dversion=210" "-Dpackaging=jar" "-Dfile=/Users/gaowenfeng/Downloads/ganymed-ssh2-build210/ganymed-ssh2-build210.jar"The final Dfile path is the real path of ganymed-ssh2-build210.jar after unzipped from the recently downloaded zipCopy the code