首页 > 其他分享 >RestUtils

RestUtils

时间:2022-10-28 21:11:28浏览次数:42  
标签:return String get RestUtils restUrl error import

import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Rest请求工具类
 */
@Component
public final class RestUtils {
    @Value("${request.appSecret}")
    private String token;

    @Value("${request.application.appId}")
    private String appId;

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    private static final Logger LOGGER = LoggerFactory.getLogger(RestUtils.class);

    private OkHttpClient client = new OkHttpClient().newBuilder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();;

    public String get(String restUrl) throws IOException {
        Request request = createRequest(restUrl).build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }

    public String get(final String restUrl, String parameters) throws IOException {
        if (StringUtils.isNotEmpty(parameters)) {
            return get(restUrl + "?" + parameters);
        }
        return get(restUrl);
    }

    public String post(String restUrl, String json, Map<String, String> headers) {
        RequestBody body = RequestBody.create(JSON, json);
        Request.Builder requestBuilder = createRequest(restUrl);
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            requestBuilder.addHeader(entry.getKey(), entry.getValue());
        }
        Request request = requestBuilder.post(body).build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (Exception e) {
            LOGGER.error("post error:", e);
        }
        return "";
    }
    private Request.Builder createRequest(String url) {
        String tokenAuth = null;
        try {
              tokenAuth = getToken();
        } catch (Exception e) {
            LOGGER.error("get token error, encoding error", e);
        }

        return new Request.Builder().url(url)
                .header("Content-Type", "application/json;charset=UTF-8")
                .addHeader("X-HW-APPKEY", "czyImZk1LvPcP+m+BgmyzA==")
                .addHeader("X-HW-ID", "app_000000035085");
    }
    private String getToken() {
        String tokenRut = null;
        try {
            String environmentRut = RegistryUtilService.findDictionaryValue("supplybisde.online_type");
            String credentialRut = token;
            String appIdRut = appId;
            // 通过SOA管控平台的API生成动态Token
            // 设置SAO管控平台环境,只有uat和pro环境
            if (!"pro".equals(environmentRut)) {
                LOGGER.info("getToken Method environmentRut");
                SoaAppTokenClientUtil.setEnvironment("uat");
            } else {
                SoaAppTokenClientUtil.setEnvironment(environmentRut);
            }
            // 将AppId和静态Token传入API,获取动态Token值
            SoaAppTokenClientUtil.initial(appIdRut, credentialRut);
            try {
                tokenRut = SoaAppTokenClientUtil.getBasicTokenByAppCredential();
            } catch (Exception ex) {
                // junit 处理
                String url = ApplicationConfigProperties.getContextProperty("umws4login.url");
                AuthenticationDelegate.initRequestURL(url);
                tokenRut = SoaAppTokenClientUtil.getBasicTokenByAppCredential();
            }
        } catch (Exception ex) {
            LOGGER.error("get token error:", ex);
        }
        return tokenRut;
    }
}

 

标签:return,String,get,RestUtils,restUrl,error,import
From: https://www.cnblogs.com/mingruifeng/p/16837498.html

相关文章