【问题标题】:java.net cannot resolve Domain namejava.net 无法解析域名
【发布时间】:2020-07-11 20:20:15
【问题描述】:

所以,我在 localhost 上做我的项目,一切都很顺利。我能够向服务器发出请求调用并从我的 android 获得响应。没问题。然后我从 AWS 得到了一个 ec2 并没有映射到任何域名。所以,当我使用 curl 或 postman 发出请求时,它工作得很好。一切都很好。但是我尝试从我的 Retrofit 发出请求的同一个 URL 显示

HTTP FAILED: java.net.UnknownHostException: Unable to resolve host "ec2-11-130-81-251.ap-south-1.compute.amazonaws.comapi": No address associated with hostname

我还确保我的手机和所有东西都允许上网。那么,从安卓手机发出网络请求时必须要有域名吗?有没有办法绕过这些事情?

如果觉得有用的话,这是我的改造单例课程。谢谢

public class ApiClient {

//    public static final String BASE_LOCAL_URL = "http://192.168.1.4:3000/";
//    public static final String BASE_LOCAL_EMULATOR_URL = "http://10.0.2.2:3000/";
        public static final String SERVIER_LOGIN="ec2-11-130-81-251.ap-south-1.compute.amazonaws.comapi";
    public static final String BASE_URL = SERVIER_LOGIN;

    private static Retrofit retrofit = null;

    private ApiClient() {


        if (retrofit != null) {
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }
    }

    public static synchronized Retrofit getClient(Context context) {


        if (retrofit == null) {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.level(HttpLoggingInterceptor.Level.BODY);


            AuthInterceptor authInterceptor = new AuthInterceptor(context);
            OkHttpClient client = new OkHttpClient.Builder().
                    addInterceptor(authInterceptor).
                    readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .addInterceptor(interceptor)
                    .build();


            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(getGson()))
                    .client(client)
                    .build();

            return retrofit;
        }


        return retrofit;
    }

    private static Gson getGson() {


        return new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").create();
    }
}

【问题讨论】:

  • 我通过在最后添加 / 来解决。大声笑
  • 如果您找到了答案,请自行回答并接受或删除帖子本身[虽然我个人不推荐这样做,因为它可能会在将来帮助其他人],以便其他人不必再次来看它,相信它还没有回答......

标签: android gson retrofit2 okhttp android-networking


【解决方案1】:

通过在您的基本 URL 中添加一个斜杠来解决。也就是说,如果您的基本 URL 是 www.some_base_url.com,那么在启动改造实例时它应该是 www.some_base_url.com/。所以。如果出现该错误,请确保在最后添加斜杠。

【讨论】:

    猜你喜欢
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 2017-04-20
    相关资源
    最近更新 更多