调取服务的工具-AsyncHttpClient的使用案例

使用场景

最近一段时间在进行电子发票的开发,设计过程中将前后端进行了分离,前端处理进行View+controller,调用后端的提供接口服务进行逻辑处理。在微服务越来越盛行的当下,越来越多的服务被供应商提供出来,例如票通电子发票的接口,微信公众号的接口,百度等的接口,我们要对对其进行调用,借用AsyncHttpClient进行调用,简单又高效。

使用案例

入我给用户发短信的时候,因短信字数限制且长url实在看着恶心,遂借用百度的服务将长地址转换为短地址代码,代码如下:

@Test
public void test() {
    Gson gson=new Gson();
    String bdshort="https://dwz.cn/admin/create";//百度提供的服务地址
    Map<String,String> map=new HashMap<>();
    map.put("url","https://weibo.com/u/6019398883/home");//长连接地址
    String request =AsyncHttpClientUtil.post(bdshort,gson.toJson(map));
    JSONObject json=JSONObject.parseObject(request);
    System.out.print(json.getString("ShortUrl"));
}

 

 这里我用到了AsyncHttpClientUtil工具类AsyncHttpClientUtil.java,代码如下:

package cn.stylefeng.guns.modular.system.util;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;


/**
 * 第三方类包AsyncHttpClient,工具类
 * @author xuchun 2017-04-07
 *
 */
public class AsyncHttpClientUtil {
	
	private final static Logger logger = LoggerFactory.getLogger(AsyncHttpClientUtil.class);
	
    private static final String DEFAULT_CHARSET = "UTF-8";

    public static final String CONTENT_TYPE_JSON="application/json;charset=UTF-8";

    public static final String CONTENT_TYPE_XML="text/xml;charset=UTF-8";

    public static final String CONTENT_TYPE_html="text/html;charset=utf-8";


    public static final String CONTENT_TYPE_FORM="application/x-www-form-urlencoded";
    /**
     * @return 返回类型:
     * @throws IOException
     * @throws UnsupportedEncodingException
     * @throws NoSuchProviderException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @description 功能描述: get 请求
     */
    public static String get(String url, Map<String, String> params, Map<String, String> headers) {
        AsyncHttpClient http = new AsyncHttpClient();
        try {
            AsyncHttpClient.BoundRequestBuilder builder = http.prepareGet(url);
            builder.setBodyEncoding(DEFAULT_CHARSET);
            if (params != null && !params.isEmpty()) {
                Set<String> keys = params.keySet();
                for (String key : keys) {
                    builder.addQueryParameter(key, params.get(key));
                }
            }

            if (headers != null && !headers.isEmpty()) {
                Set<String> keys = headers.keySet();
                for (String key : keys) {
                    builder.addHeader(key, params.get(key));
                }
            }
            logger.info("----------------AsyncHttpClientUtil-get--------------");
            logger.info("----------------请求url:"+url);
//            logger.info("----------------请求param:"+WebUtil.parseFastJson(params));
            Future<Response> f = builder.execute();
           // f.get().
            String body = f.get().getResponseBody(DEFAULT_CHARSET);

            logger.info("----------------请求返回状态码:"+f.get().getStatusCode());
            logger.info("----------------请求返回内容:"+body);
            return body;
        } catch (Exception e) {
            logger.error("error:"+e);
            return null;
        } finally {
            if(http!=null){
                http.close();
            }
        }
    }

    /**
     * @return 返回类型:
     * @throws IOException
     * @throws UnsupportedEncodingException
     * @throws NoSuchProviderException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @description 功能描述: get 请求
     */
    public static String get(String url) {
        return get(url, null);
    }

    /**
     * @return 返回类型:
     * @throws IOException
     * @throws NoSuchProviderException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws UnsupportedEncodingException
     * @description 功能描述: get 请求
     */
    public static String get(String url, Map<String, String> params) {
        return get(url, params, null);
    }

    /**
     * @return 返回类型:
     * @throws IOException
     * @throws NoSuchProviderException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @description 功能描述: POST 请求
     */
    public static String post(String url, Map<String, String> params) {
        AsyncHttpClient http = new AsyncHttpClient();
        try {
            AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
            builder.setBodyEncoding(DEFAULT_CHARSET);
            if (params != null && !params.isEmpty()) {
                Set<String> keys = params.keySet();
                for (String key : keys) {
                    builder.addParameter(key, params.get(key)==null?"":params.get(key));
                }
            }
            logger.info("----------------AsyncHttpClientUtil-post--------------");
            logger.info("----------------请求url:"+url);
//            logger.info("----------------请求param:"+WebUtil.parseFastJson(params));
            Future<Response> f = builder.execute();
            logger.info("----------------请求返回状态码:"+f.get().getStatusCode());
            String body = f.get().getResponseBody(DEFAULT_CHARSET);
            logger.info("----------------请求返回内容:"+body);
            return body;
        } catch (Exception e) {
            logger.error("error:"+e);
            return null;
        } finally {
            if(http!=null){
                http.close();
            }
        }
    }



    
    /**
     * @return 返回类型:
     * @throws IOException
     * @throws NoSuchProviderException
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @description 功能描述: POST 请求
     */
    public static String post(String url, Map<String, String> params,Boolean isProxy,Map<String,String> proxyMap){
        AsyncHttpClient http = new AsyncHttpClient();
        try {
            AsyncHttpClient.BoundRequestBuilder builder =http.preparePost(url);
            //设置代理配置
            if(isProxy){
                ProxyServer proxyServer=
                        new ProxyServer(
                                proxyMap.get("proxyIp"),
                                Integer.valueOf(proxyMap.get("proxyPort")),
                                proxyMap.get("userName"),
                                proxyMap.get("password"));
                builder.setProxyServer(proxyServer);
            }

            builder.setBodyEncoding(DEFAULT_CHARSET);
            if (params != null && !params.isEmpty()) {
                Set<String> keys = params.keySet();
                for (String key : keys) {
                    builder.addParameter(key, params.get(key)==null?"":params.get(key));
                }

            }
            //此header千万不能加上,因为会导致接收方,获取不到请求参数
            //builder.addHeader("Content-type", "text/html;charset=utf-8");
            logger.info("----------------AsyncHttpClientUtil-post--------------");
            logger.info("----------------是否使用代理服务器:"+isProxy+"--------------");
            logger.info("----------------请求url:"+url);
//            logger.info("----------------请求param:"+WebUtil.parseFastJson(params));
            Future<Response> f = builder.execute();
            logger.info("----------------请求返回状态码:"+f.get().getStatusCode());
            String body = f.get().getResponseBody(DEFAULT_CHARSET);
            logger.info("----------------请求返回内容:"+body);

            return body;
        } catch (Exception e) {
            logger.error("error:"+e);
            return null;
        }finally {
            if(http!=null){
                http.close();
            }
        }
    }




    public static String post(String url, String s) {
        AsyncHttpClient http = new AsyncHttpClient();
        try {
            AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
            builder.setBodyEncoding(DEFAULT_CHARSET);
            builder.addHeader("Content-type", "application/json;charset=UTF-8");
            builder.setBody(s);
            logger.info("----------------AsyncHttpClientUtil-post-body--------------");
            logger.info("----------------请求url:"+url);
            logger.info("----------------请求body:"+s);
            Future<Response> f = builder.execute();
            logger.info("----------------请求返回状态码:"+f.get().getStatusCode());
            String body = f.get().getResponseBody(DEFAULT_CHARSET);
            logger.info("----------------请求返回内容:"+body);
            return body;
        } catch (Exception e) {
            logger.error("error:"+e);
            return null;
        } finally {
            if(http!=null){
                http.close();
            }
        }
    }


    public static String postBody(String url, String s,String contentType) {
        logger.info("------------url:"+url);
        AsyncHttpClient http = new AsyncHttpClient();
        try {
            AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
            builder.setBodyEncoding(DEFAULT_CHARSET);
            builder.addHeader("Content-type", contentType);
            builder.setBody(s);
            logger.info("----------------请求url:"+url);
            logger.info("----------------请求body:"+s);
            Future<Response> f = builder.execute();
            String body = f.get().getResponseBody(DEFAULT_CHARSET);
            logger.info("----------------请求返回内容:"+body);
            return body;
        } catch (Exception e) {
            logger.error("error:"+e);
            return null;
        } finally {
            if(http!=null){
                http.close();
            }
        }
    }





    /**
     * io流下载文件
     * xuchun
     * 2017-12-26
     * @param url
     * @param contentType
     * @param output
     * @return
     */
    public static boolean getToFile(String url, String contentType, FileOutputStream output) {
        logger.info("------------下载文件url:"+url);
        AsyncHttpClient http = new AsyncHttpClient();
        try {
            AsyncHttpClient.BoundRequestBuilder builder = http.preparePost(url);
            builder.setBodyEncoding(DEFAULT_CHARSET);
            builder.addHeader("Content-type", contentType);
            Future<Response> f = builder.execute();
            /*String str=f.get().getResponseBody(DEFAULT_CHARSET);
            logger.info(str);*/
            logger.info("----------------请求返回状态码:"+f.get().getStatusCode());
            if(f.get().getStatusCode()==200){
                InputStream instream = f.get().getResponseBodyAsStream();
                if(instream!=null){
                    try {
                        byte[] tmp = new byte[4096];
                        int l;
                        while((l = instream.read(tmp)) != -1) {
                            output.write(tmp, 0, l);
                        }
                    } finally {
                        if(instream!=null){
                            instream.close();
                        }
                        if(output!=null){
                            output.close();
                        }

                    }
                }
            }

            logger.info("------------文件下载完成,请查看文件目录");
            return true;

        } catch (Exception e) {
            logger.error("error:"+e);
            return false;
        } finally {
            if(http!=null){
                http.close();
            }
        }
    }


}

经过翻代码我们可以看到AsyncHttpClient使用的future,Java的Future模式涉及了异步和多线程,有趣的大家可以了解下。参考地址:http://www.cnblogs.com/cz123/p/7693064.html

结束语

开发人员可以关注以下公众号,我会定期分享javaweb和数据分析的相关知识,谢谢

 

 

java 工具包, async-http-client-1.6.3.jar com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class com.google.gson.FieldNamingStrategy.class com.google.gson.Gson.class com.google.gson.GsonBuilder.class com.google.gson.InstanceCreator.class com.google.gson.JsonArray.class com.google.gson.JsonDeserializationContext.class com.google.gson.JsonDeserializer.class com.google.gson.JsonElement.class com.google.gson.JsonIOException.class com.google.gson.JsonNull.class com.google.gson.JsonObject.class com.google.gson.JsonParseException.class com.google.gson.JsonParser.class com.google.gson.JsonPrimitive.class com.google.gson.JsonSerializationContext.class com.google.gson.JsonSerializer.class com.google.gson.JsonStreamParser.class com.google.gson.JsonSyntaxException.class com.google.gson.LongSerializationPolicy.class com.google.gson.TreeTypeAdapter.class com.google.gson.TypeAdapter.class com.google.gson.TypeAdapterFactory.class com.google.gson.annotations.Expose.class com.google.gson.annotations.SerializedName.class com.google.gson.annotations.Since.class com.google.gson.annotations.Until.class com.google.gson.internal.ConstructorConstructor.class com.google.gson.internal.Excluder.class com.google.gson.internal.JsonReaderInternalAccess.class com.google.gson.internal.LazilyParsedNumber.class com.google.gson.internal.ObjectConstructor.class com.google.gson.internal.Primitives.class com.google.gson.internal.Streams.class com.google.gson.internal.StringMap.class com.google.gson.internal.UnsafeAllocator.class com.google.gson.internal.bind.ArrayTypeAdapter.class com.google.gson.internal.bind.CollectionTypeAdapterFactory.class com.google.gson.internal.bind.DateTypeAdapter.class com.google.gson.internal.bind.JsonTreeReader.class com.google.gson.internal.bind.JsonTreeWriter.class com.google.gson.internal.bind.MapTypeAdapterFactory.class com.google.gson.internal.bind.ObjectTypeAdapter.c
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值