【问题标题】:UnknownHostException: name or service not knownUnknownHostException:名称或服务未知
【发布时间】:2016-01-06 20:18:22
【问题描述】:

我正在尝试使用 com.squareup.okhttp 中的 OkHttpClient 从 API 返回一些数据。我遇到了一些我最终能够克服的错误,但我无法克服这个主机异常错误,而且这里似乎没有什么具体到足以解决我的情况。

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

代码

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();
    }
}

输出

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$1.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$1.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)

【问题讨论】:

  • 我遇到了和你一样的问题。你能找到解决办法吗?? @Jordan Macey-Smith?

标签: java exception host okhttp


【解决方案1】:

对于像“java.net.UnknownHostException: [hostname]”这样的错误

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

sudo vim /etc/hosts

改行如下:

127.0.0.1  localhost

到:

127.0.0.1  [hostname] localhost

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

sudo ifconfig eth0 down&&sudo ifconfig eth0 up

希望对你有帮助!

【讨论】:

    【解决方案2】:

    扩展 zhenbo xu 的出色答案,这是我在 EC2 中使用 sed 自动执行的操作。

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

    注意,为了允许变量扩展,单引号结束并在子shell调用周围重新开始。

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

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

    【讨论】:

      【解决方案3】:

      由于您尚未发布您的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);
              }
          }
      

      然后在onCreate里面:

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

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

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

      P/S:确保您在 AndroidManifest.xml 文件中设置了 &lt;uses-permission android:name="android.permission.INTERNET" /&gt;

      【讨论】:

        猜你喜欢
        • 2016-11-10
        • 2013-08-08
        • 2019-07-07
        • 1970-01-01
        • 2021-08-19
        • 2018-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多