This question already has answers here:
Networking code sometimes throws UnknownHostException
                                
                                    (4个答案)
                                
                        
                7个月前关闭。
            
        

为什么会抛出UnknownHostException?

    parameters = "user=akirus&pass=1234&version=1";
    String result = excutePost("http://russianimperial.ru/minecraft/loginServer.php", parameters);

  public static String excutePost(String targetURL, String urlParameters) {
      HttpURLConnection connection = null;
      try {
          URL url = new URL(targetURL);
          connection = (HttpURLConnection)url.openConnection();

          connection.setRequestMethod("POST");
          connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
          connection.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
          connection.setRequestProperty("Content-Language", "en-US");

          connection.setUseCaches(false);
          connection.setDoInput(true);
          connection.setDoOutput(true);

          DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
          wr.writeBytes(urlParameters);
          wr.flush();
          wr.close();

          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));

          StringBuffer response = new StringBuffer();
          String line;
          while ((line = rd.readLine()) != null) {
              response.append(line);
              response.append('\r');
          }
          rd.close();

          String str1 = response.toString();
          return str1;
     }catch (Exception e) {
         e.printStackTrace();
         return null;
     }finally {
         if (connection != null)
             connection.disconnect();
     }
  }


网址http://russianimperial.ru/minecraft/loginServer.php有效。早期它的工作很棒。 UnknownHostException扔在了这个地方InputStream is = connection.getInputStream();
在javadoc中写到,当协议不支持输入时,connection.getInputStream()可以抛出此异常,但是我认为http支持输入。

最佳答案

JavaDoc

UnknownHostException是


  抛出以表明主机的IP地址不能被使用
  决心


在提出SO问题之前先做。

关于java - UnknownHostException ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14136416/

10-12 06:16