http请求工具类

1,httpUtils工具类

public class HttpUtils {
    public HttpUtils() {
    }

    public static String sendGet(String url, Map<String, String> parameters) {
        String result = "";
        BufferedReader in = null;
        StringBuffer sb = new StringBuffer();
        String params = "";

        try {
            Iterator var6;
            String name;
            String full_url;
            if (parameters.size() == 1) {
                var6 = parameters.keySet().iterator();

                while(var6.hasNext()) {
                    name = (String)var6.next();
                    if (parameters.get(name) != null) {
                        sb.append(name).append("=").append(URLEncoder.encode((String)parameters.get(name), "UTF-8"));
                    }
                }

                params = sb.toString();
            } else {
                var6 = parameters.keySet().iterator();

                while(var6.hasNext()) {
                    name = (String)var6.next();
                    if (parameters.get(name) != null) {
                        sb.append(name).append("=").append(URLEncoder.encode((String)parameters.get(name), "UTF-8")).append("&");
                    }
                }

                full_url = sb.toString();
                params = full_url.substring(0, full_url.length() - 1);
            }

            full_url = url + "?" + params;
            System.out.println(full_url);
            URL connURL = new URL(full_url);
            HttpURLConnection httpConn = (HttpURLConnection)connURL.openConnection();
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            httpConn.connect();
            Map<String, List<String>> headers = httpConn.getHeaderFields();
            Iterator var10 = headers.keySet().iterator();

            while(var10.hasNext()) {
                String key = (String)var10.next();
                System.out.println(key + "\t:\t" + headers.get(key));
            }

            String line;
            for(in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8")); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var20) {
            var20.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException var19) {
                var19.printStackTrace();
            }

        }

        return result;
    }

    public static String sendPost(String url, Map<String, String> parameters) {
        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;
        StringBuffer sb = new StringBuffer();
        String params = "";

        try {
            Iterator var7;
            String name;
            if (parameters.size() == 1) {
                var7 = parameters.keySet().iterator();

                while(var7.hasNext()) {
                    name = (String)var7.next();
                    if (parameters.get(name) != null && parameters.get(name) != null) {
                        sb.append(name).append("=").append(URLEncoder.encode((String)parameters.get(name), "UTF-8")).append("&");
                    }
                }

                params = sb.toString();
            } else {
                var7 = parameters.keySet().iterator();

                while(var7.hasNext()) {
                    name = (String)var7.next();
                    if (parameters.get(name) != null) {
                        sb.append(name).append("=").append(URLEncoder.encode((String)parameters.get(name), "UTF-8")).append("&");
                    }
                }

                String temp_params = sb.toString();
                params = temp_params.substring(0, temp_params.length() - 1);
            }

            URL connURL = new URL(url);
            HttpURLConnection httpConn = (HttpURLConnection)connURL.openConnection();
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            out = new PrintWriter(httpConn.getOutputStream());
            out.write(params);
            out.flush();

            String line;
            for(in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8")); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var18) {
            var18.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var17) {
                var17.printStackTrace();
            }

        }

        return result;
    }
}
2,HttpclientX工具类


public class HttpclientX {
    private static final Logger logger = LoggerFactory.getLogger(HttpclientX.class);
    private String userAgent = BrowserUtils.getRandomBrowser();
    private SSLs.SSLProtocolVersion sslProtocolVersion;
    private static Integer retryTime = 5;
    private static Integer poolMaxTotal = 500;
    private static Integer defaultMaxPerRoute = 100;
    private Integer connectionRequestTimeout;
    private Integer connectTimeout;
    private Integer socketTimeout;
    private Map<String, String> headers;
    private String cookies;
    private static PoolingHttpClientConnectionManager cm = null;
    private RequestConfig reqConfig;
    private CredentialsProvider credsProvider;
    private HttpClientContext localContext;
    private HttpMethods httpMethods;
    private static HCB hcb = HCB.custom();
    private ProxyX proxyX;
    private Proxy proxy;
    private Authenticator proxyAuthenticator;

    public HttpclientX setProxyX(final ProxyX proxyX) {
        this.proxyX = proxyX;
        if (proxyX != null) {
            System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
            AuthCache authCache = new BasicAuthCache();
            authCache.put(proxyX.getProxy(), new BasicScheme());
            this.localContext = HttpClientContext.create();
            this.localContext.setAuthCache(authCache);
            this.proxy = new Proxy(Type.HTTP, new InetSocketAddress(proxyX.getHostname(), proxyX.getPort()));
            if (proxyX.isNeedUserPsd()) {
                this.credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxyX.getProxyUser(), proxyX.getProxyPassword()));
                java.net.Authenticator.setDefault(new java.net.Authenticator() {
                    private final PasswordAuthentication authentication = new PasswordAuthentication(proxyX.getProxyUser(), proxyX.getProxyPassword().toCharArray());

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return this.authentication;
                    }
                });
                this.proxyAuthenticator = new Authenticator() {
                    public Request authenticate(Route route, Response response) throws IOException {
                        String credential = Credentials.basic(proxyX.getProxyUser(), proxyX.getProxyPassword());
                        return response.request().newBuilder().header("Proxy-Authorization", credential).build();
                    }
                };
            }
        }

        return this;
    }

    public HttpclientX setSSL(SSLs.SSLProtocolVersion sslProtocolVersion) {
        this.sslProtocolVersion = sslProtocolVersion;
        return this;
    }

    public HttpclientX setHeaders(Map<String, String> headers) {
        this.headers = headers;
        return this;
    }

    public HttpclientX setUserAgent(String userAgent) {
        this.userAgent = userAgent;
        return this;
    }

    public HttpclientX setCookies(String cookies) {
        this.cookies = cookies;
        return this;
    }

    public HttpclientX setTimeOut(Integer time) {
        this.connectionRequestTimeout = time;
        this.connectTimeout = time;
        this.socketTimeout = time;
        return this;
    }

    public HttpclientX setConnectionRequestTimeout(Integer time) {
        this.connectionRequestTimeout = time;
        return this;
    }

    public HttpclientX setConnectTimeout(Integer time) {
        this.connectTimeout = time;
        return this;
    }

    public HttpclientX setSocketTimeout(Integer time) {
        this.socketTimeout = time;
        return this;
    }

    public void setHttpMethods(HttpMethods httpMethods) {
        this.httpMethods = httpMethods;
    }

    private HttpclientX() {
        this.sslProtocolVersion = SSLProtocolVersion.SSLv3;
        this.connectionRequestTimeout = 10000;
        this.connectTimeout = 10000;
        this.socketTimeout = 10000;
        this.reqConfig = null;
        this.credsProvider = new BasicCredentialsProvider();
        this.localContext = null;
        this.httpMethods = HttpMethods.GET;
    }

    public static HttpclientX create() {
        return new HttpclientX();
    }

    public HttpConfig config() throws Exception {
        HttpHeader httpHeader = HttpHeader.custom().userAgent(this.userAgent);
        if (this.headers != null && this.headers.size() > 0) {
            Iterator var2 = this.headers.entrySet().iterator();

            while(var2.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var2.next();
                httpHeader.other((String)entry.getKey(), (String)entry.getValue());
            }
        }

        if (StringUtils.isNotBlank(this.cookies)) {
            httpHeader.cookie(this.cookies);
        }

        Header[] headers = httpHeader.build();
        hcb = hcb.sslpv(this.sslProtocolVersion).ssl().retry(retryTime);
        RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setConnectionRequestTimeout(this.connectionRequestTimeout).setConnectTimeout(this.connectTimeout).setSocketTimeout(this.socketTimeout).setExpectContinueEnabled(false);
        HttpClientBuilder httpClientBuilder = hcb.setUserAgent(this.userAgent).setConnectionManager(cm);
        httpClientBuilder.disableAutomaticRetries();
        if (this.proxyX != null) {
            requestConfigBuilder = requestConfigBuilder.setProxy(this.proxyX.getProxy());
            if (this.proxyX.isNeedUserPsd()) {
                httpClientBuilder.setDefaultCredentialsProvider(this.credsProvider);
            }
        }

        this.reqConfig = requestConfigBuilder.build();
        HttpClient client = httpClientBuilder.build();
        HttpConfig config = HttpConfig.custom().headers(headers).timeout(this.reqConfig).encoding("utf-8").client(client);
        if (this.httpMethods != null) {
            config.method(this.httpMethods);
        }

        if (this.proxyX != null) {
            config.context(this.localContext);
        }

        if (config.map() != null) {
            config.map().clear();
        }

        return config;
    }

    public String doGet(String url) {
        try {
            return HttpClientUtil.get(this.config().url(url));
        } catch (Exception var3) {
            logger.error("get错误", var3);
            return null;
        }
    }

    public String doGet(String url, Map<String, Object> params) {
        try {
            return HttpClientUtil.get(this.config().url(this.getFullUrl(url, params)));
        } catch (Exception var4) {
            logger.error("get错误", var4);
            return null;
        }
    }

    public HttpResult doGetAndGetResponse(String url, Map<String, Object> params) {
        try {
            return HttpClientUtil.executeResult(this.config().method(HttpMethods.GET).url(url).map(params));
        } catch (Exception var4) {
            logger.error("get错误", var4);
            return null;
        }
    }

    public HttpResult doPostAndGetResponse(String url, Map<String, Object> params) {
        try {
            return HttpClientUtil.executeResult(this.config().method(HttpMethods.POST).url(url).map(params));
        } catch (Exception var4) {
            logger.error("post错误", var4);
            return null;
        }
    }

    public HttpResult doPostAndGetResponse(String url, String json) {
        try {
            return HttpClientUtil.executeResult(this.config().method(HttpMethods.POST).url(url).json(json));
        } catch (Exception var4) {
            logger.error("post错误", var4);
            return null;
        }
    }

    public String doPost(String url, Map<String, Object> params) {
        try {
            return HttpClientUtil.post(this.config().url(url).map(params));
        } catch (Exception var4) {
            logger.error("post错误", var4);
            return null;
        }
    }

    public String doPost(String url, String json) {
        try {
            return HttpClientUtil.post(this.config().url(url).json(json));
        } catch (Exception var4) {
            logger.error("post错误", var4);
            return null;
        }
    }

    public String doGetJsonp(String url, Map<String, Object> parameters) {
        try {
            return HttpClientUtil.get(this.config().url(this.getFullUrl(url, parameters)));
        } catch (Exception var4) {
            logger.error("get错误", var4);
            return null;
        }
    }

    private String getFullUrl(String url, Map<String, Object> parameters) {
        String params = (String)Optional.ofNullable(parameters).map((ps) -> {
            return (String)ps.entrySet().stream().map((entry) -> {
                return (String)entry.getKey() + "=" + StringUtil.urlEncode((String)Optional.ofNullable(entry.getValue()).map((v) -> {
                    return v.toString();
                }).orElse(""));
            }).collect(Collectors.joining("&"));
        }).orElse("");
        if (StrUtil.isNotEmpty(params)) {
            url = url + "?" + params;
        }

        return url;
    }

    public String doGetJsonpReturnJson(String url, Map<String, Object> parameters) {
        return this.doGetJsonpReturnJson(url, parameters, (String)null);
    }

    public String doGetJsonpReturnJson(String url, Map<String, Object> parameters, String callbackKey) {
        if (StringUtils.isBlank(callbackKey)) {
            callbackKey = "callback";
        }

        if (parameters.get(callbackKey) == null) {
            return null;
        } else {
            String callback = parameters.get(callbackKey).toString();
            String result = this.doGetJsonp(url, parameters);
            String jsonStr = result.replace(callback, "");
            if (!StringUtils.isBlank(jsonStr) && jsonStr.contains("(")) {
                jsonStr = jsonStr.substring(jsonStr.indexOf("(") + 1, jsonStr.lastIndexOf(")"));
                return jsonStr;
            } else {
                return null;
            }
        }
    }

    public static Map<String, Object> addJsonpCallback(Map<String, Object> parameters) {
        String time = String.valueOf((new Date()).getTime());
        String callback = "jQuery351018003419644615448_" + time;
        parameters.put("callback", callback);
        parameters.put("_", time);
        return parameters;
    }

    public boolean download(String url, File file) {
        FileOutputStream fileOutputStream = null;

        boolean var5;
        try {
            makeFolderExists(file.getParentFile());
            fileOutputStream = new FileOutputStream(file);
            HttpClientUtil.down(this.config().url(url).out(fileOutputStream));
            if (file.exists()) {
                boolean var4 = true;
                return var4;
            }

            return false;
        } catch (Exception var16) {
            logger.error("download错误,URL=" + url, var16);
            var5 = false;
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception var15) {
                logger.error("download错误,URL=" + url, var15);
            }

        }

        return var5;
    }

    public OutputStream download(String url, FileOutputStream fileOutputStream) {
        Object var4;
        try {
            HttpClientUtil.down(this.config().url(url).out(fileOutputStream));
            FileOutputStream var3 = fileOutputStream;
            return var3;
        } catch (Exception var14) {
            logger.error("download错误,URL=" + url, var14);
            var4 = null;
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception var13) {
                logger.error("download错误,URL=" + url, var13);
            }

        }

        return (OutputStream)var4;
    }

    public OutputStream customDownload(String url, FileOutputStream fileOutputStream) {
        Object var4;
        try {
            HttpClientUtil.down(HttpConfig.custom().url(url).out(fileOutputStream));
            FileOutputStream var3 = fileOutputStream;
            return var3;
        } catch (Exception var14) {
            logger.error("download错误", var14);
            var4 = null;
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            } catch (Exception var13) {
                logger.error("download错误", var13);
            }

        }

        return (OutputStream)var4;
    }

    public boolean hutoolDownload(String url, File file) {
        HttpResponse response = null;

        try {
            boolean var5;
            try {
                makeFolderExists(file.getParentFile());
                HttpRequest request = HttpRequest.get(url).setConnectionTimeout(this.connectTimeout).setReadTimeout(this.socketTimeout).setFollowRedirects(true).setMaxRedirectCount(5);
                if (MapUtil.isNotEmpty(this.headers)) {
                    request.headerMap(this.headers, true);
                }

                if (this.proxy != null) {
                    request.setProxy(this.proxy);
                }

                response = request.executeAsync();
                if (response.isOk()) {
                    response.writeBody(file);
                    if (file.exists()) {
                        var5 = true;
                        return var5;
                    }
                }

                var5 = false;
                return var5;
            } catch (Exception var9) {
                logger.error("hutoolDownload下载失败,URL=" + url, var9);
                var5 = false;
                return var5;
            }
        } finally {
            IoUtil.close(response);
        }
    }

    public boolean fastDownload(String url, File file) {
        InputStream is = null;

        try {
            makeFolderExists(file.getParentFile());
            FastHttpClientBuilder fastHttpClientBuilder = FastHttpClient.newBuilder().connectTimeout((long)this.connectTimeout, TimeUnit.MILLISECONDS).readTimeout((long)this.connectTimeout, TimeUnit.MILLISECONDS);
            if (this.proxyX != null) {
                fastHttpClientBuilder.proxy(this.proxy).proxyAuthenticator(this.proxyAuthenticator);
            }

            GetBuilder builder = (GetBuilder)fastHttpClientBuilder.build().get().url(url);
            if (this.headers != null && this.headers.size() > 0) {
                Iterator var6 = this.headers.entrySet().iterator();

                while(var6.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry)var6.next();
                    builder.addHeader((String)entry.getKey(), (String)entry.getValue());
                }
            }

            io.itit.itf.okhttp.Response response = builder.build().execute();
            boolean var15;
            if (response.isSuccessful()) {
                FileUtil.saveContent((InputStream)is, file);
                if (file.exists()) {
                    var15 = true;
                    return var15;
                }
            }

            var15 = false;
            return var15;
        } catch (Exception var11) {
            logger.error("fastDownload下载失败,URL=" + url, var11);
            boolean var5 = false;
            return var5;
        } finally {
            IoUtil.close((Closeable)is);
        }
    }

    public static void makeFolderExists(File folder) {
        if (!folder.exists()) {
            folder.mkdirs();
        }

    }

    static {
        try {
            hcb = HCB.custom().timeout(1000).pool(poolMaxTotal, defaultMaxPerRoute);
            ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
            LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContexts.custom().loadTrustMaterial((KeyStore)null, new TrustSelfSignedStrategy()).build(), NoopHostnameVerifier.INSTANCE);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.create().register("http", plainsf).register("https", sslsf).build();
            cm = new PoolingHttpClientConnectionManager(registry);
            cm.setMaxTotal(poolMaxTotal);
            cm.setDefaultMaxPerRoute(defaultMaxPerRoute);
        } catch (Exception var3) {
            logger.error("HCB静态初始化错误", var3);
        }

    }

    public static class ProxyX {
        private HttpHost proxy;
        private String hostname;
        private int port;
        private String proxyUser;
        private String proxyPassword;
        private boolean needUserPsd = false;

        public ProxyX(String hostname, int port, String scheme) {
            this.proxy = new HttpHost(hostname, port, scheme);
        }

        public ProxyX(HttpHost proxy) {
            this.proxy = proxy;
        }

        public ProxyX(HttpHost proxy, String proxyUser, String proxyPassword) {
            this.proxy = proxy;
            this.proxyUser = proxyUser;
            this.proxyPassword = proxyPassword;
            this.needUserPsd = true;
        }

        public ProxyX(String hostname, int port, String scheme, String proxyUser, String proxyPassword) {
            this.proxy = new HttpHost(hostname, port, scheme);
            this.hostname = hostname;
            this.port = port;
            this.proxyUser = proxyUser;
            this.proxyPassword = proxyPassword;
            this.needUserPsd = true;
        }

        public HttpHost getProxy() {
            return this.proxy;
        }

        public void setProxy(HttpHost proxy) {
            this.proxy = proxy;
        }

        public String getProxyUser() {
            return this.proxyUser;
        }

        public void setProxyUser(String proxyUser) {
            this.proxyUser = proxyUser;
        }

        public String getProxyPassword() {
            return this.proxyPassword;
        }

        public void setProxyPassword(String proxyPassword) {
            this.proxyPassword = proxyPassword;
        }

        public boolean isNeedUserPsd() {
            return this.needUserPsd;
        }

        public void setNeedUserPsd(boolean needUserPsd) {
            this.needUserPsd = needUserPsd;
        }

        public String getHostname() {
            return this.hostname;
        }

        public void setHostname(String hostname) {
            this.hostname = hostname;
        }

        public int getPort() {
            return this.port;
        }

        public void setPort(int port) {
            this.port = port;
        }
    }
}
 

3,封装统一请求工具类,用到上面的httpUtils,HttpclientX两个工具类。


public class HttpRequestCommandExe {

    @SneakyThrows
    public PageResult executeGet(String requestUrl, Map params, Class<? extends PageResult> resultType) {

        if ( Objects.isNull(params)){
            params = new HashMap();
        }
        log.info("请求url={},params={}", requestUrl, params);
        String resultString = "";
        JSONObject resultJSON = new JSONObject();
        //防止请求出错
        try {
            //防止请求出错
            resultString = HttpUtils.sendGet(requestUrl,params);
            //解析json结果防止报错
            resultJSON = JSONObject.parseObject(resultString);
            //判断是否请求200
            if (Objects.nonNull(resultJSON)) {
                boolean successRequest = Objects.equals(RequestConstant.SUCCUESS_CODE, resultJSON.getInteger("code"));
                if (!successRequest) {
                    log.error("请求出错,请求的url是{},参数是{},结果是{}", requestUrl, params, resultString);
                    return resultType.newInstance();
                }
            }

            //进入正式的业务
            String dataStr = null;
            if (Objects.nonNull(resultJSON))
             dataStr = resultJSON.getString("data");
            return JSON.parseObject(dataStr, PageResult.class);
        } catch (Exception e) {
            log.error("请求出错,请求的url是{},参数是{},结果是{},异常是{}", requestUrl, params, resultString, e);

            return resultType.newInstance();
        }
    }


    public <T> List<T> executeGetPageResultList(String requestUrl, Map params, Class<T> resultType) {
        if (Objects.isNull(params)) {
            params = new HashMap();
        }
        log.info("请求url={},params={}", requestUrl, params);
        String resultString = "";
        JSONObject resultJSON = null;
        try {
            //防止请求出错
            resultString = HttpUtils.sendGet(requestUrl, params);
            //解析json结果防止报错
            resultJSON = JSONObject.parseObject(resultString);
            //判断是否请求200,非500则安徽才能得到正确业务
            if (Objects.nonNull(resultJSON)) {
                boolean successRequest = Objects.equals(RequestConstant.SUCCUESS_CODE, resultJSON.getInteger("code"));
                if (!successRequest) {
                    log.error("请求出错,请求的url是{},参数是{},结果是{}", requestUrl, params, resultString);
                    return Collections.emptyList();
                }
            }

            //进入正式的业务
            String data = null;
            if (Objects.nonNull(resultJSON)){
                 data = resultJSON.getString("data");
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSONObject.parseObject(data);
            String dataArray = jsonObject.getString("rows");
            return JSON.parseArray(dataArray, resultType);
        } catch (JSONException e) {
            log.error("json解析出错,请求的url是{},参数是,结果是{},异常是{}", requestUrl, params, resultString, e);

            return Collections.emptyList();
        } catch (Exception e) {
            log.error("请求出错,请求的url是{},参数是{},结果是{},异常是{}", requestUrl, params, resultString, e);

            log.error("", e);
            return Collections.emptyList();
        }


    }

    public R<?> executePostResult(String requestUrl, String paramJson) {
        if (Objects.isNull(paramJson)) {
            paramJson="{}";
        }
        try {
            String resultString = HttpclientX.create().setConnectTimeout(30000).doPost(requestUrl, paramJson);

            //解析json结果为R
            return JSON.parseObject(resultString, R.class);

        } catch (JSONException e) {
            log.error("json解析出错,请求的url是{},参数是,结果是{},异常是{}", requestUrl, paramJson, paramJson, e);

        } catch (Exception e) {
            log.error("请求出错,请求的url是{},参数是{},结果是{},异常是{}", requestUrl, paramJson, paramJson, e);

        }
        return R.fail();
    }


    public <T> List<T> executePostPageResultList(String requestUrl, String paramJson, Class<T> resultType) {
        if (Objects.isNull(paramJson)) {
            paramJson="{}";
        }
        try {
            String resultString="";
            JSONObject resultJSON= new JSONObject();
            //防止请求出错
            resultString = HttpclientX.create().setConnectTimeout(30000).doPost(requestUrl, paramJson);
            //解析json结果防止报错
            resultJSON = JSONObject.parseObject(resultString);
            //判断是否请求200,非500则安徽才能得到正确业务
            if (Objects.nonNull(resultJSON)) {
                boolean successRequest = Objects.equals(RequestConstant.SUCCUESS_CODE, resultJSON.getInteger("code"));
                if (!successRequest) {
                    log.error("请求出错,请求的url是{},参数是{},结果是{}", requestUrl, paramJson, resultString);
                    return Collections.emptyList();
                }
            }
            //进入正式业务
            String data = null;
            if (Objects.nonNull(resultJSON)){
                data = resultJSON.getString("data");
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSONObject.parseObject(data);
            String dataArray = jsonObject.getString("rows");
            return JSON.parseArray(dataArray, resultType);
        } catch (JSONException e) {
            log.error("json解析出错,请求的url是{},参数是,结果是{},异常是{}", requestUrl, paramJson, paramJson, e);

            return Collections.emptyList();
        } catch (Exception e) {
            log.error("请求出错,请求的url是{},参数是{},结果是{},异常是{}", requestUrl, paramJson, paramJson, e);

            return Collections.emptyList();
        }
    }


    public <T> List<T> executeGetList(String requestUrl, Map params, Class<T> resultType) {
        if (Objects.isNull(params)) {
            params = new HashMap();
        }
        log.info("请求url={},params={}", requestUrl, params);
        String resultString = "";
        JSONObject resultJSON = null;
        try {
            //防止请求出错
            resultString = HttpclientX.create().doGet(requestUrl, params);
            //解析json结果防止报错
            resultJSON = JSON.parseObject(resultString);
            //判断是否请求200,非500则安徽才能得到正确业务
            if (Objects.nonNull(resultJSON)) {
                boolean successRequest = Objects.equals(RequestConstant.SUCCUESS_CODE, resultJSON.getInteger("code"));
                if (!successRequest) {
                    log.error("请求出错,请求的url是{},参数是{},结果是{}", requestUrl, params, resultString);
                    return Collections.emptyList();
                }
            }

            //进入正式的业务
            String data = null;
            if (Objects.nonNull(resultJSON)){
                 data = resultJSON.getString("data");
            }
            return JSON.parseArray(data, resultType);
        } catch (JSONException e) {
            log.error("json解析出错,请求的url是{},参数是,结果是{},异常是{}", requestUrl, params, resultString, e);

            return Collections.emptyList();
        } catch (Exception e) {
            log.error("请求出错,请求的url是{},参数是{},结果是{},异常是{}", requestUrl, params, resultString, e);

            log.error("", e);
            return Collections.emptyList();
        }


    }

    public <T> List<T> executePostGetList(String requestUrl, String paramJson, Class<T> resultType) {
        if (Objects.isNull(paramJson)) {
            paramJson="{}";
        }
        try {
            String resultString="";
            JSONObject resultJSON= new JSONObject();
            //防止请求出错
            resultString = HttpclientX.create().setConnectTimeout(30000).doPost(requestUrl, paramJson);
            //解析json结果防止报错
            resultJSON = JSONObject.parseObject(resultString);
            //判断是否请求200,非500则安徽才能得到正确业务
            if (Objects.nonNull(resultJSON)) {
                boolean successRequest = Objects.equals(RequestConstant.SUCCUESS_CODE, resultJSON.getInteger("code"));
                if (!successRequest) {
                    log.error("请求出错,请求的url是{},参数是{},结果是{}", requestUrl, paramJson, resultString);
                    return Collections.emptyList();
                }
            }
            //进入正式业务
            //进入正式的业务
            String data = null;
            if (Objects.nonNull(resultJSON)){
                 data = resultJSON.getString("data");
            }
            return JSON.parseArray(data, resultType);
        } catch (JSONException e) {
            log.error("json解析出错,请求的url是{},参数是,结果是{},异常是{}", requestUrl, paramJson, paramJson, e);

            return Collections.emptyList();
        } catch (Exception e) {
            log.error("请求出错,请求的url是{},参数是{},结果是{},异常是{}", requestUrl, paramJson, paramJson, e);

            return Collections.emptyList();
        }
    }

}
 

4,在你的业务代码调用;

  @ApiOperation(value = "xxxxxxxxxxx接口", notes = "xxxxxxxxxxx接口", httpMethod = "GET")
  @GetMapping("/xxxxxxxMethod")
    public R<List<xxxxxxDTO>> getRegionTreeByLevelForRpc(@RequestParam("areaLevel") Integer areaLevel) {
        String url = XXXXXHost + "/XXXXX/XXXX/XXXX/XXXXX";
        Map map = new HashMap<>();
        map.put("areaLevel",areaLevel);
        log.info("请求URL是{},接口的请求报文为={}", url, map);
        HttpRequestCommandExe requestCommandExe = new HttpRequestCommandExe();
        List<xxxxxxDTO> result = requestCommandExe.executeGetList(url, map, xxxxxxDTO.class);
        log.info("接口请求第三方返回值为={}", result);
        return R.ok(result);
    }

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JB091

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值