package com.slient.lambda;
import java.io.IOException;
import java.util.Arrays;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class CallBackTest {
public static void main(String[] args) throws ClientProtocolException, IOException {
_JqueryAjax.ajax(
"https://www.baidus.com",
"POST",
true,
(xhr) -> {
//对外暴露的对于请求的设置
},
(res) -> {
System.out.println("Success CallBack >>> " + res);
},
(err) -> {
System.out.println("Error CallBack >>> " + err.getMessage());
}
);
System.out.println("================================测试异步分割线================================");
}
}
/**
* Jdk1.8,模拟JQ.ajax的简单实现
* @author zhengfu
*
*/
class _JqueryAjax {
//beforeSend
@FunctionalInterface
interface _IBeforeSend {
void beforeSend(HttpRequestBase httpRequestBase);
}
//success
@FunctionalInterface
interface _ISuccess {
void success(Object obj);
}
//error
@FunctionalInterface
interface _IError {
void error(Throwable err);
}
//
public static void ajax(
String url,
String type,
boolean async,
_IBeforeSend b,
_ISuccess s,
_IError e) {
//模拟异步
if(async) {
new Thread(() -> {
send(url,type,b,s,e);
}).start();
}else {
send(url,type,b,s,e);
}
}
//
private static void send(
String url,
String type,
_IBeforeSend b,
_ISuccess s,
_IError e) {
//
CloseableHttpClient client = HttpClientBuilder.create().build();
//
HttpRequestBase httpRequestBase = null;
switch (type) {
case "POST":
httpRequestBase = new HttpPost(url);
break;
case "GET":
httpRequestBase = new HttpGet(url);
break;
}
//
b.beforeSend(httpRequestBase);
//execute
CloseableHttpResponse response = null;
try {
//
response = client.execute(httpRequestBase);
//
s.success(EntityUtils.toString(response.getEntity()));
} catch (Exception exception) {
//
e.error(exception);
} finally {
close(response);
close(client);
}
}
//关闭资源
private static <T extends java.io.Closeable> void close(T t) {
try {
if(t != null)
t.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}