java - 使用 http 改造连接超时
问题描述
嗨,我正在尝试使用改造和okhttp3将我的 android 客户端连接到我的服务器,但我在改造时遇到问题,我应该添加一个基本 URL,但是当 URL 具有SSL(https://)时,它可以完美地工作,但是当我想要在没有 SSL (http://)的情况下完成确切的工作有时我有超时错误(10 次中有 5 次)我真的无法理解我的后端是Symfony框架的问题,它在我的手机浏览器上使用或不使用 SSL和在我的计算机浏览器或Postman应用程序上,这是我的改造客户端:
public class apiClient {
private static Retrofit retrofit = null;
private static final String CACHE_CONTROL = "Cache-Control";
public static Retrofit initClient(){
String text = "";
byte[] data = android.util.Base64.decode(apiClient.retrofit_id, android.util.Base64.DEFAULT);
try {
text = new String(data, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(text)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
public static void setClient(retrofit2.Response<ApiResponse> response, Activity activity, PrefManager prf){
if (response.isSuccessful()) {
if (response.body().getCode().equals(202)) {
Toasty.error(activity, response.body().getMessage(), Toast.LENGTH_SHORT).show();
SplashActivity.adapteActivity(activity);
} else {
prf.setString("formatted","true");
}
}
}
public static String LoadClientData(Activity activity){
return activity.getApplicationContext().getPackageName();
}
public static void FormatData(final Activity activity,Object o){
try {
final PrefManager prf = new PrefManager(activity.getApplication());
if (!prf.getString("formatted").equals("true")) {
if (apiClient.check(activity)) {
Retrofit retrofit=apiClient.initClient();
apiRest service = retrofit.create(apiRest.class);
Call<ApiResponse> callback = service.setWallpaper(apiClient.LoadClientData(activity));
callback.enqueue(new Callback<ApiResponse>() {
@Override
public void onResponse(Call<ApiResponse> call, retrofit2.Response<ApiResponse> response) {
apiClient.setClient(response,activity,prf);
}
@Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
}
});
}
}
}catch (Exception e){
if (o!=null){
return;
}else{
}
}
}
public static boolean check(Activity activity){
final PrefManager prf = new PrefManager(activity.getApplication());
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
if (prf.getString("LAST_DATA_LOAD").equals("")) {
prf.setString("LAST_DATA_LOAD", strDate);
} else {
String toyBornTime = prf.getString("LAST_DATA_LOAD");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date oldDate = dateFormat.parse(toyBornTime);
System.out.println(oldDate);
Date currentDate = new Date();
long diff = currentDate.getTime() - oldDate.getTime();
long seconds = diff / 1000;
if (seconds >15) {
prf.setString("LAST_DATA_LOAD", strDate);
return true;
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return false;
}
public static Retrofit getClient() {
if (retrofit==null) {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.addInterceptor( provideHttpLoggingInterceptor() )
.addInterceptor( provideOfflineCacheInterceptor() )
.addNetworkInterceptor( provideCacheInterceptor() )
.cache( provideCache() )
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
OkHttp3Downloader okHttp3Downloader = new OkHttp3Downloader(okHttpClient);
Picasso picasso = new Picasso.Builder(App.getInstance())
.downloader(okHttp3Downloader)
.build();
Picasso.setSingletonInstance(picasso);
retrofit = new Retrofit.Builder()
.baseUrl(Config.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
private static Cache provideCache ()
{
Cache cache = null;
try
{
cache = new Cache( new File( App.getInstance().getCacheDir(), "wallpaper-cache" ),
10 * 1024 * 1024 ); // 10 MB
}
catch (Exception e)
{
Timber.e( e, "Could not create Cache!" );
}
return cache;
}
private static HttpLoggingInterceptor provideHttpLoggingInterceptor ()
{
HttpLoggingInterceptor httpLoggingInterceptor =
new HttpLoggingInterceptor( new HttpLoggingInterceptor.Logger()
{
@Override
public void log (String message)
{
Timber.d( message );
}
} );
httpLoggingInterceptor.setLevel( BuildConfig.DEBUG ? HEADERS : NONE );
return httpLoggingInterceptor;
}
public static Interceptor provideCacheInterceptor ()
{
return new Interceptor()
{
@Override
public Response intercept (Chain chain) throws IOException
{
Response response = chain.proceed( chain.request() );
// re-write response header to force use of cache
CacheControl cacheControl = new CacheControl.Builder()
.maxAge( 2, TimeUnit.SECONDS )
.build();
return response.newBuilder()
.header( CACHE_CONTROL, cacheControl.toString() )
.build();
}
};
}
public static String retrofit_id = "aHR0cDovL2xpY2Vuc2UucmlzdGFuYS5jb20vYXBpLw==";
public static Interceptor provideOfflineCacheInterceptor ()
{
return new Interceptor()
{
@Override
public Response intercept (Chain chain) throws IOException
{
Request request = chain.request();
if ( !App.hasNetwork() )
{
CacheControl cacheControl = new CacheControl.Builder()
.maxStale( 30, TimeUnit.DAYS )
.build();
request = request.newBuilder()
.cacheControl( cacheControl )
.build();
}
return chain.proceed( request );
}
};
}
}
解决方案
您应该添加网络安全配置以允许非 ssl 连接。https://developer.android.com/training/articles/security-config
推荐阅读
- java - SimpleJdbcCall 是“多线程的”是什么意思?
- javascript - 网站上一节(里)的刷新功能
- rpm - rpm -qa 显示已安装软件包,但 rpm -e 显示未安装
- android - 使用 Android BLE Gatt 时如何接收重新连接通知
- linux - 无需桌面管理器即可显示的 Linux 绘图
- firebase - 在 Firebase 控制台中查看数据库
- javascript - 如何在 SVG 动画上获得最佳性能(鼠标悬停时 FPS 下降)
- java - 使用 websocket 获取数据流时的主要问题是什么?
- amazon-web-services - 通过 CLI 阻止所有对象在 S3 中的公共访问
- android - 如何解决 Flutter Activity 中 BOTTOM OVERFLOWED BY 84 PIXLES 的问题?