Java后端的http post异步请求(带回调函数)

package com.xxx.framework.common.util;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.protocol.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class HttpAsyncUtils {

	private static Logger log = LoggerFactory.getLogger(HttpAsyncUtils.class);

    /**
     * POST方式调用(带回调函数)
     *
     * @param url
     * @param params 参数为NameValuePair键值对对象
* List params = new ArrayList();
* params.add(new BasicNameValuePair(name, value)); * @param header 请求头部 * @param needHeader 是否需要头部 * @param callback 回调方法
* 返回值为 FutureCallback 的方法
* 方法内返回 new FutureCallback() {重写 completed, failed, cancelled 方法} * @return 响应字符串 */ public static void httpPostCallback(CloseableHttpAsyncClient httpclient, String url, List params, Map header, boolean needHeader, FutureCallback callback) throws Exception { HttpPost post = new HttpPost(url); URL testUrl = new URL(url); HttpURLConnection urlConnection = (HttpURLConnection)testUrl.openConnection(); try { urlConnection.connect(); } catch (IOException e) { throw new ConnectException(e.getMessage()); } finally { urlConnection.disconnect(); } if(needHeader){ for(String key : header.keySet()){ post.setHeader(key, header.get(key)); } } // 传入HttpPost httpclient.start(); try{ log.info("HttpAsyncUtils httpPostCallback Param : {}", params); if (params != null) { post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } httpclient.execute(post, callback); } catch(Exception e) { e.printStackTrace(); } finally { } } }

调用

List param = new ArrayList<>();
param.add(new BasicNameValuePair("id", ""));
   
Map map = getHeadersInfo(request);
   
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
HttpAsyncUtils.httpPostCallback(
    httpclient,
    url,
    param,
    map,
    true,
    callback(httpclient)
);
   
/**
 * 异步请求完成的回调方法
 * @return
 */
private FutureCallback callback(CloseableHttpAsyncClient httpclient) {
    return new FutureCallback() {
        @Override
        public void completed(final HttpResponse response) {
            try {
                String responseJson = null;
                responseJson = EntityUtils.toString(response.getEntity(), "UTF-8");
                
                log.info("callback completed response content is : {}", responseJson);
            } catch (IOException e) {
                e.printStackTrace();
                log.info("callback completed errorMsg : {}", e.getMessage());
            } finally {
                try {
                    httpclient.close();
                    log.info("callback completed httpclient close");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void failed(Exception ex) {
            try {
                httpclient.close();
                log.info("callback failed httpclient close");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void cancelled() {
            try {
                httpclient.close();
                log.info("callback cancelled httpclient close");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
}

/**
 * 处理请求头部信息
 * @param request 请求
 * @return
 */
public static Map getHeadersInfo(HttpServletRequest request) {
    Map map = new HashMap();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        String value = request.getHeader(key);
        map.put(key, value);
    }
    return map;
}

你可能感兴趣的:(Java)