如何用java判断客户机能不能连接因特网,给段代码,谢谢!!! 越简单越好

解决方案 »

  1.   

    向个靠谱点的url发送数据请求,看看是否有返回结果
      

  2.   

    写个函数或者方法调用ping测试一下,
      

  3.   

    受3楼启发,以前用httpclient的时候,貌似是可以,找个百度Google之类的
    发送HTTP请求,不过你得让这段代码在客户端执行才行
      

  4.   

    import java.net.InetAddress;
    import java.net.Socket;public class netTest { private String  serverURL = "www.baidu.com";
    private int  port = 80;
    public netTest(){
    InetAddress addr;
    try {
    addr = InetAddress.getByName(serverURL);
    Socket socket = new Socket(addr,port);
    System.out.println(socket.toString());
    System.out.println("Connected to internet!"); //成功连接网络
    } catch (Exception e) {
    System.out.println("Cannot connect to internet!"); //不能连接因特网
    }

    }

    public static void main(String[] argus){
    new netTest();
    }
    }
      

  5.   

    使用apache下的httpclient package test;
    import java.io.IOException;
    import org.apache.commons.httpclient.*;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    public class GetSample{
      public static void main(String[] args) {
      //构造HttpClient的实例
      HttpClient httpClient = new HttpClient();
      //创建GET方法的实例
      GetMethod getMethod = new GetMethod("http://www.baidu.com");
      getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
        new DefaultHttpMethodRetryHandler());
      try {
       //执行getMethod
       int statusCode = httpClient.executeMethod(getMethod);
       if (statusCode != HttpStatus.SC_OK) {
        System.err.println("Method failed: "
          + getMethod.getStatusLine());
       }
       //读取内容 
       byte[] responseBody = getMethod.getResponseBody();
       //处理内容
       System.out.println(new String(responseBody));
      } catch (HttpException e) {
       //发生致命的异常,可能是协议不对或者返回的内容有问题
       System.out.println("Please check your provided http address!");
       e.printStackTrace();
      } catch (IOException e) {
       //发生网络异常
       e.printStackTrace();
      } finally {
       //释放连接
       getMethod.releaseConnection();
      }
     }
    }
      

  6.   


    public static void main(String args[]) {
    try {
    URL url = new URL("http://www.baid.com");
    URL url2 = new URL("http://www.basdfsdid.com");
    HttpURLConnection httpCon = (HttpURLConnection) url
    .openConnection();
    System.out.println("Response code is " + httpCon.getResponseCode());

    httpCon = (HttpURLConnection) url2.openConnection();
    // 200:链接成功
    System.out.println("Response code is " + httpCon.getResponseCode());
    } catch (IOException e) {
    System.out.println("地址不存在");
    // e.printStackTrace();
    } }