Java Spring 怎么异步发送post请求?
如果你跟我一样用的Spring 4.0 版本或以上的话,最简单的方式就是使用
AsyncRestTemplate
我用的是fastJson,来post Json 数据
源码如下,URL 是post 链接, 第二个参数是数据, 第三个参数可以不要
public StringBuffer postHttpJsonDataAsyn(String URL, JSONObject jsonObject, final JSONObject responseJsonMap) throws IOException {
// 发送异步post , 非阻塞, 发送完无需等待结果返回
AsyncRestTemplate client = new AsyncRestTemplate();
ListenableFuture<ResponseEntity<String>> listenableFuture = client.postForEntity(URL, new HttpEntity<Object>(jsonObject), String.class);
listenableFuture.addCallback(new SuccessCallback<ResponseEntity<String>>() {
@Override
public void onSuccess(ResponseEntity<String> result) {
System.out.println("("+result.getStatusCode()+ ":"+result.getStatusCode().getReasonPhrase()+ "):"+result.getBody());
}
}, new FailureCallback() {
@Override
public void onFailure(Throwable ex) {
System.out.println(ex);
}
});
return new StringBuffer("finish postHttpJsonDataAsyn post");
}
@Override
public StringBuffer postHttpStringDataAsyn(String URL, String postStr, JSONObject results) throws IOException {
// 发送异步post , 非阻塞, 发送完无需等待结果返回
AsyncRestTemplate client = new AsyncRestTemplate();
ListenableFuture<ResponseEntity<String>> listenableFuture = client.postForEntity(URL, new HttpEntity<Object>(postStr), String.class);
listenableFuture.addCallback(new SuccessCallback<ResponseEntity<String>>() {
@Override
public void onSuccess(ResponseEntity<String> result) {
System.out.println("("+result.getStatusCode()+ ":"+result.getStatusCode().getReasonPhrase()+ "):"+result.getBody());
}
}, new FailureCallback() {
@Override
public void onFailure(Throwable ex) {
ex.printStackTrace();
System.out.println(ex);
}
});
return new StringBuffer("finish postHttpStringDataAsyn post");
}