get请求带body的formdata非json实现AsyncHttpClient解决

最近项目遇到get请求带body的formdata情况,百度了一下只有json的解决方案,没有formdata的,看了AsyncHttpClient相关源码,把json的解决方案修改了下成功了记录下

 <dependency>
          <groupId>org.asynchttpclient</groupId>
            <artifactId>async-http-client</artifactId>
            <version>2.2.0</version>
            </dependency>
/**
     * 执行异步HTTP请求
     */
    public String asyncRequest(String url,List<Part> params) {
        AsyncHttpClient c = new DefaultAsyncHttpClient();
        Future<Response> f = c.prepareGet(url).setBodyParts(
                params)
                .addHeader("authorization",TokenManager.getToken())
                .execute(new AsyncCompletionHandler<Response>() {
                    @Override
                    public Response onCompleted(Response response) {
                        return response;
                    }

                    @Override
                    public void onThrowable(Throwable t) {
                        throw new RuntimeException("exception");
                    }
                });
        Response response=null;
        try {
            long startTime = System.currentTimeMillis();
            while (true){
                response = f.get();
                if(response!=null){
                    break;
                }else {
                    long endTime = System.currentTimeMillis();
                    // 大于8秒认为查询数据失败
                    if((endTime-startTime)/1000>8){
                        throw new RuntimeException("exception");
                    }
                }
            }
        } catch (Exception e) {
            logger.error("数据异常");
        }
        return response==null?"":response.getResponseBody();
    }
List<Part> params = new ArrayList<>();
       
        params.add(new StringPart("startTime",startTime));
        params.add(new StringPart("endTime",endTime));

 

posted @ 2022-03-02 08:56  枫树湾河桥  阅读(639)  评论(0编辑  收藏  举报
Live2D