android - 如何解决服务连接失败?
问题描述
我想访问特定 URL 中的服务 ...。我使用改造来获取它,但它给了我与 URL 的错误连接...而 URL 在 chrome 中处于活动状态。
在我写的代码中???而是更正一个^__^(此代码是APIClient类)并确保我以正确的方式工作,我在模拟站点中使用相同的json文件构建了一个api ....它是有效的,所以任何人都可以帮助请给我
public static final String BASE_URL = "http://111.222.1.12:0000/???/???/????/";
//database
public static final String BASE_URL2 = "http://www.mocky.io/v2/";
public static Boolean URL=true;
private static Retrofit retrofit = null;
public static Retrofit getClient(){
if (retrofit==null) {
if(URL)
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
else
{
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL2)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
return retrofit;
}
解决方案
您好,您可以尝试使用我的 ApiClient,我正在使用 rxJava,因此您需要根据需要重新设计 APIClient
public class ApiClient {
private static Retrofit retrofit = null;
private static int REQUEST_TIMEOUT = 120;
private static OkHttpClient okHttpClient;
public static Retrofit getClient(Context context) {
if (okHttpClient == null)
initOkHttp(context);
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(API_PATH)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
private static void initOkHttp(Context context) {
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
.tlsVersions(TlsVersion.TLS_1_2)
.cipherSuites(
CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256)
.build();
OkHttpClient.Builder httpClient = new OkHttpClient().newBuilder()
.connectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(interceptor);
httpClient.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Request-Type", "Android")
.addHeader("Content-Type", "application/json");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
okHttpClient = httpClient.build();
}
public static void resetApiClient() {
retrofit = null;
okHttpClient = null;
}
}
希望这个参考可以帮助你解决你的问题
推荐阅读
- nativescript - CLI 更新后 Nativescript Sidekick 不会启动
- python - 如何为 tkinter 中的每个按钮状态设置个人图片?
- c++ - 如何从 QT C++ 中的对话框向父主窗口发送密钥
- php - symfony 上的单元测试问题
- c - clang 中是否有固定宽度的浮点类型?
- javascript - 同一服务的零星 400(错误请求)
- java - 将 JSF/CDI 依赖注入到 ActionListener
- tensorflow - Windows 10,CUDA 9,: ..\src\THC\THCG 处的 CUDA 运行时版本的 CUDA 驱动程序版本不足
- php - Instagram API 端点
- sql - 如何检查空值的连接值并在其他表中查找