美文网首页
AsyncHttpClient发送HTTP请求

AsyncHttpClient发送HTTP请求

作者: 刘书生 | 来源:发表于2019-11-06 18:25 被阅读0次
    var httpGet = httpClient.prepareGet(authServer.getInter().getEndpoint())
                        .addQueryParam(APP_CREDENTIAL,token)
                        .addQueryParam(APIID,apiId)
                        .setReadTimeout(MoreObjects.firstNonNull(authServer.getSocketTimeout(), DEFAULT_SOCKET_TIMEOUT))
                        .setRequestTimeout(MoreObjects.firstNonNull(authServer.getRequestTimeout(), DEFAULT_REQUEST_TIMEOUT));
    
     httpGet.execute(userProfileHandler).toCompletableFuture().whenComplete((value, cause)->{
                    if (cause != null) {
                        if(log.isErrorEnabled()){
                            log.error("Remote invocation fail:{}",cause);
                        }
                    } else {
                        if(StringUtils.equals(value.getCode(),SUCCESS_CODE)){
                            cache.put(AUTH_SERVER_NAME,finalToken,value);
                            ctx.pipeline().remove(applicationContext.getBean(OAuthHandler.class));
                        }else if(StringUtils.equals(value.getCode(),LOCAL_CODE)){
                            ctx.pipeline().addAfter(ctx.name(), OAuthHandler.class.getName(), applicationContext.getBean(OAuthHandler.class));
                        }else if(StringUtils.equals(value.getCode(),FORBIDDEN_CODE)){
                            var forResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN);
                            forResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, "0");
                            ctx.writeAndFlush(forResponse).addListener(ChannelFutureListener.CLOSE);
                            return;
                        }else if(StringUtils.equals(value.getCode(),UNAUTHORIZED_CODE)){
                            var UnaResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
                            UnaResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, "0");
                            ctx.writeAndFlush(UnaResponse).addListener(ChannelFutureListener.CLOSE);
                            return;
                        }else{
                            // ignore
                        }
                    }
                });
    
    static class UserProfileHandler implements AsyncHandler<InterAuthModel>{
            private org.asynchttpclient.HttpResponseStatus responseStatus;
            private HttpHeaders responseHeaders;
            private ByteBuf responseBody = Unpooled.buffer();
            private Exception cause;
            private Gson gson = new GsonBuilder().create();
    
            @Override
            public State onStatusReceived(org.asynchttpclient.HttpResponseStatus responseStatus) throws Exception {
                this.responseStatus = responseStatus;
    
                return State.CONTINUE;
            }
    
            @Override
            public State onHeadersReceived(HttpHeaders httpHeaders) throws Exception {
                this.responseHeaders = httpHeaders;
    
                return State.CONTINUE;
            }
    
            @Override
            public State onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                if (bodyPart.length() > 0) {
                    this.responseBody.writeBytes(bodyPart.getBodyPartBytes());
                }
    
                return State.CONTINUE;
            }
    
            @Override
            public void onThrowable(Throwable t) {
                if (t instanceof Exception) {
                    cause = (Exception)t;
                } else {
                    cause = new RuntimeException(t);
                }
            }
    
            @Override
            public InterAuthModel onCompleted() throws Exception {
                if (cause != null) {
                    throw cause;
                }
                if (responseStatus == null) {
                    throw new IllegalStateException("AuthServer not responsed.");
                }
                if (responseStatus.getStatusCode() != 200) {
                    String stringBody = null;
                    if (responseBody != null && responseBody.readableBytes()  > 0) {
                        stringBody = responseBody.toString(Charsets.UTF_8);
                    }
    
                    if (!Strings.isNullOrEmpty(stringBody)) {
                        throw new IllegalStateException("AuthServer responsed code=" + responseStatus.getStatusCode() + ", resposne body=" + stringBody);
                    } else {
                        throw new IllegalStateException("AuthServer responsed code=" + responseStatus.getStatusCode());
                    }
                }
    
    
                if (responseBody == null || responseBody.readableBytes() <= 0) {
                    throw new IllegalStateException("AuthServer responsed with empty body");
                }
    
                Map<String, Object> responseAsMap = gson.fromJson(responseBody.toString(Charsets.UTF_8), Map.class);
                try {
                    ReferenceCountUtil.safeRelease(responseBody);
                } catch (Throwable ex) {
                    // ignore
                }
                var profile = new InterAuthModel();
                String token = (String)responseAsMap.get("token");
                String code = (String)responseAsMap.get("code");
                profile.addAttributes(responseAsMap);
                profile.addAttribute(InterAuthModel.KEY_TOKEN, token);
                profile.addAttribute(InterAuthModel.KEY_CODE, code);
    
                return profile;
            }
        }
    

    相关文章

      网友评论

          本文标题:AsyncHttpClient发送HTTP请求

          本文链接:https://www.haomeiwen.com/subject/rgcpbctx.html