springboot+retorfit+okhttp集成

pom.xml

       <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>retrofit</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.squareup.retrofit2</groupId>
            <artifactId>converter-jackson</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>logging-interceptor</artifactId>
            <version>3.8.1</version>
        </dependency>

HttpApi 工具类

public class HttpApi {


	private static Retrofit retorfit = null;
	private static OkHttpClient okHttpClient = null;

	private static Retrofit noAuthRetorfit = null;
	private static OkHttpClient noAuthOkHttpClient = null;

	@Value("${http-api.client-url}")
	private String clientUrl;
	public static String CLIENT_URL;


	@PostConstruct
	private void init() {
		CLIENT_URL = this.clientUrl;
		okhttpClientBuilder();
		retorfitBuilder();

		noAuthOkhttpClientBuilder();
		noAuthRetorfitBuilder();
	}

	private void noAuthOkhttpClientBuilder() {
		noAuthOkHttpClient = new OkHttpClient.Builder()
				.connectTimeout(30, TimeUnit.SECONDS)
				.readTimeout(120, TimeUnit.SECONDS)
				.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
				.hostnameVerifier(SSLUtils.trustAllHostVerifier())
				.sslSocketFactory(SSLUtils.simpleSslSocketFactory(), SSLUtils.trustAllCerManager())
				.build();
	}

	private void okhttpClientBuilder() {
		okHttpClient = new OkHttpClient.Builder()
				.connectTimeout(30, TimeUnit.SECONDS)
				.readTimeout(120, TimeUnit.SECONDS)
				.addInterceptor(new AuthInterceptor())
				.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
				.hostnameVerifier(SSLUtils.trustAllHostVerifier())
				.sslSocketFactory(SSLUtils.simpleSslSocketFactory(), SSLUtils.trustAllCerManager())
				.build();
	}

	private void noAuthRetorfitBuilder() {
		noAuthRetorfit = new Retrofit.Builder()
				.baseUrl(CLIENT_URL + "/")
				.addConverterFactory(JacksonConverterFactory.create(JsonUtils.getMapper()))
				.client(noAuthOkHttpClient)
				.build();
	}

	private void retorfitBuilder() {
		retorfit = new Retrofit.Builder()
				.baseUrl(CLIENT_URL + "/")
				.addConverterFactory(JacksonConverterFactory.create(JsonUtils.getMapper()))
				.client(okHttpClient)
				.build();
	}

	public static  <T> T create(Class<T> service) {
		return retorfit.create(service);
	}

	public static <T> T noAuthCreate(Class<T> service) {
		return noAuthRetorfit.create(service);
	}
}
public class SSLUtils {

    public static final String SSL_PROTOCOL = "TLSV1.2";

    public static X509TrustManager trustAllCerManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    public static SSLSocketFactory simpleSslSocketFactory() {
        try {
            TrustManager trustAll = trustAllCerManager();
            TrustManager[] trustManagers = new TrustManager[]{trustAll};
            SSLContext sslContext = SSLContext.getInstance(SSL_PROTOCOL);
            sslContext.init(null, trustManagers, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (Exception ex) {
            return null;
        }
    }

    public static HostnameVerifier trustAllHostVerifier() {
        return new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
    }
}
public class JsonUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        MAPPER.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    }

    public static ObjectMapper getMapper() {
        return MAPPER;
    }

    public static String obj2JsonStr(Object object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static String obj2JsonStrPretty(Object object) {
        try {
            return MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static JsonNode obj2JsonNode(Object object) {
        try {
            return MAPPER.valueToTree(object);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static <T> T jsonStr2Obj(String json, Class<T> type) {
        try {
            return MAPPER.readValue(json, type);
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
    }

    public static <T> T jsonNode2Obj(JsonNode jsonNode, Class<T> type) {
        try {
            return MAPPER.convertValue(jsonNode, type);
        } catch (Exception var3) {
            throw new RuntimeException(var3);
        }
    }

    public static <T> List<T> jsonStrToList(String json, Class<T> cls) {
        try {
            return MAPPER.readValue(json, getCollectionType(List.class, cls));
        } catch (Exception e) {
            String className = cls.getSimpleName();
        }
        return null;
    }

    private static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return MAPPER.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }
}

鉴权

public class AuthInterceptor implements Interceptor {

	private Map<String, String> token = new HashMap();

	@Override
	public Response intercept(Chain chain) throws IOException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String accessToken = null;
		if (!token.containsKey(Constants.ACCESS_TOKEN)) {
			accessToken = token.get(Constants.ACCESS_TOKEN);
			AuthRequest authRequest = new AuthRequest();
			authRequest.setUserId("user123");
			authRequest.setPassword("123456");
			retrofit2.Response<HttpResponse<Authentication>> response =
					HttpApi.noAuthCreate(HttpApiService.class).getToken(authRequest).execute();
			if (response.isSuccessful()) {
				accessToken = response.body().getData().getAccess_token();
				token.put(Constants.ACCESS_TOKEN, accessToken);
			}
		} else {
			try {
				accessToken = token.get(Constants.ACCESS_TOKEN);
				long timeLimit = 50 * 60 * 1000;
				long refreshTime = System.currentTimeMillis() - Integer.valueOf(Constants.REFRESH_TIME);
				if (System.currentTimeMillis() - refreshTime > timeLimit) {
					AuthRequest authRequest = new AuthRequest();
					authRequest.setUserId("user123");
					authRequest.setPassword("123456");
					retrofit2.Response<HttpResponse<Authentication>> response =
							HttpApi.noAuthCreate(HttpApiService.class).getToken(authRequest).execute();
					if (response.isSuccessful()) {
						accessToken = response.body().getData().getAccess_token();
						token.put(Constants.ACCESS_TOKEN, accessToken);
					}
				}
			} catch (Exception ex) {
				log.error("Exception::", ex);
			}
		}
		if (!StringUtils.isEmpty(accessToken)) {
			Request request = chain.request();
			request = request.newBuilder()
					.addHeader("token", accessToken)
					.build();
			return chain.proceed(request);
		}
		return null;
	}
}

接口定义

public interface HttpApiService {
	@POST("etcd/ins/auth/token")
	Call<HttpResponse<Authentication>> getToken(@Body AuthRequest authRequest);

	@GET("etcd/ins/get")
	Call<HttpResponse<String>> queryEtcd(@Query("key") String key);

	@DELETE("etcd/ins/del/{etcdId}")
	Call<Void> delEtcd(@Path("etcdId") String etcdId);

}

调用

public class OkhttpController {

	@GetMapping("/getEtcd")
	public String get(@RequestParam(value = "key", required = true) String key) throws IOException {
		Response<HttpResponse<String>> response = HttpApi.create(HttpApiService.class).queryEtcd(key).execute();
		if (response.isSuccessful()) {
			return response.body().getData();
		}
		return "";
	}

	@DeleteMapping("/del/{etcdId}")
	public boolean del(@PathVariable(value = "etcdId") String etcdId) throws IOException {
		Response<Void> response = HttpApi.create(HttpApiService.class).delEtcd(etcdId).execute();
		if (response.isSuccessful()) {
			return true;
		}
		return false;
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值