Java UnknownHostException: 名称或服务未知

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33028842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:10:59  来源:igfitidea点击:

UnknownHostException: name or service not known

javaexceptionhostokhttp

提问by Jordan Macey-Smith

I'm attempting to return some data from an API using OkHttpClient in com.squareup.okhttp. I've run into a few errors that i have eventually been able to overcome but i can't get past this host exception error and nothing on here seems to be specific enough to my case to be able to solve.

我正在尝试使用 com.squareup.okhttp 中的 OkHttpClient 从 API 返回一些数据。我遇到了一些我最终能够克服的错误,但我无法克服这个主机异常错误,这里的任何内容似乎都没有足够具体到我的案例能够解决。

Below is the code i have attempted along with the output with it, if anyone has any idea how to overcome the error i would appreciate it.

下面是我尝试过的代码及其输出,如果有人知道如何克服错误,我将不胜感激。

CODE

代码

public void connect() {         
    OkHttpClient client = new OkHttpClient();

    com.squareup.okhttp.Request request = new com.squareup.okhttp.Request.Builder()
    .url("https://socialweb-analytics.lcloud.com/api/public/reports/jobs?companyKey=ato")
    .get()
    .addHeader("authorization", "Basic c2RidXNpbmVzc2FuYWx5dGljc0BhdG8uZ292LmF1OkFuYWx5dGljezEh")
    .addHeader("cache-control", "no-cache")
    .addHeader("postman-token", "65ef5553-77b5-053f-9c01-4fdf76bdc92f")
    .build();

    System.out.println(request.toString());

    try {
        Response response = client.newCall(request).execute();
        System.out.println(response);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

OUTPUT

输出

Request{method=GET, url=https://socialweb-analytics.lcloud.com/api/public/reports/jobs?companyKey=ato, tag=null}
java.net.UnknownHostException: socialweb-analytics.lcloud.com: Name or service not known
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress.lookupAllHostAddr(InetAddress.java:922)
    at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1314)
    at java.net.InetAddress.getAllByName0(InetAddress.java:1267)
    at java.net.InetAddress.getAllByName(InetAddress.java:1183)
    at java.net.InetAddress.getAllByName(InetAddress.java:1119)
    at com.squareup.okhttp.internal.Network.resolveInetAddresses(Network.java:29)
    at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:187)
    at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:156)
    at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:98)
    at com.squareup.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:344)
    at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:327)
    at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:245)
    at com.squareup.okhttp.Call.getResponse(Call.java:267)
    at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:224)
    at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:195)
    at com.squareup.okhttp.Call.execute(Call.java:79)
    at technical_services.persistence.lithium.LithiumDataStore.connect1(LithiumDataStore.java:127)
    at application.lithium_etl.LithiumTestController.main(LithiumTestController.java:24)

回答by BNK

Since you have not posted your code that how your connect()called, so please refer to my following working code

由于您还没有发布您如何connect()调用的代码,因此请参考我的以下工作代码

    private class StringRequest extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://socialweb-analytics.lcloud.com/api/public/reports/jobs?companyKey=ato")
                    .addHeader("authorization", "Basic c2RidXNpbmVzc2FuYWx5dGljc0BhdG8uZ292LmF1OkFuYWx5dGljezEh")
                    .addHeader("cache-control", "no-cache")
                    .addHeader("postman-token", "65ef5553-77b5-053f-9c01-4fdf76bdc92f")
                    .build();
            try {
                Response response = client.newCall(request).execute();
                return response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            System.out.println(s);
        }
    }

Then inside onCreate:

然后在onCreate里面:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTextView = (TextView) findViewById(R.id.textView);
    new StringRequest().execute();
}

My app run and got the following result (perhaps because of expired/invalid token):

我的应用程序运行并得到以下结果(可能是因为令牌过期/无效):

I/System.out: {"code":500,"message":"There was an error processing your request. It has been logged (ID a2f28b587b2f9dcc)."}

P/S: make sure you have set <uses-permission android:name="android.permission.INTERNET" />inside AndroidManifest.xmlfile

P/S: 请确保您已设置<uses-permission android:name="android.permission.INTERNET" />内部AndroidManifest.xml文件

回答by zhenbo xu

For error like "java.net.UnknownHostException: [hostname]"

对于类似“java.net.UnknownHostException: [hostname]”的错误

The reason is your hostname is not in /etc/hosts, The solution is simple:

原因是你的主机名不在 /etc/hosts 中,解决方法很简单:

sudo vim /etc/hosts

change the line looks like:

改变线看起来像:

127.0.0.1  localhost

to:

到:

127.0.0.1  [hostname] localhost

Save and exit. If the problem still exist, may be you need to restart or run :

保存并退出。如果问题仍然存在,可能是您需要重新启动或运行:

sudo ifconfig eth0 down&&sudo ifconfig eth0 up

Hope it can help you!

希望能帮到你!

回答by dragon788

Expanding on zhenbo xu's great answer this is what I did to automate things with sedin EC2.

扩展 zhenbo xu 的精彩回答,这是我sed在 EC2 中使用自动化所做的工作。

sudo sed -i -e '/127.0.0.1/ s/\(localhost\)/'$(hostname)' \1/' /etc/hosts

sudo sed -i -e '/127.0.0.1/ s/\(localhost\)/'$(hostname)' \1/' /etc/hosts

Note that to allow variable expansion the single quotes end and restart around the subshell call.

请注意,为了允许变量扩展,单引号结束并围绕 subshel​​l 调用重新启动。

hostnameis an executable on some Linux systems (but maybe not all, so you can use an environment variable instead,or remove the quotes around the subshell and use static string).

hostname是某些 Linux 系统上的可执行文件(但可能不是全部,因此您可以改用环境变量,或删除子 shell 周围的引号并使用静态字符串)。

The \1is sedmagic, it puts the "captured" search string (s/search/replacement/) in the escaped parentheses back into the replacement string.

\1sed神奇,它将转义括号中的“捕获”搜索字符串(s/search/replacement/)放回替换字符串中。