jwmwdxxx 2010-04-11 01:38
浏览 194
已采纳

处理一个异常

public static void test(String host,int port) throws HttpException, IOException {

HttpClient client = new HttpClient();

// 设置代理服务器地址和端口

//client.getHostConfiguration().setProxy("221.214.208.17", 3128);

client.getHostConfiguration().setProxy(host, port);
// 使用 GET 方法 ,如果服务器需要通过 HTTPS 连接,那只需要将下面 URL 中的 http 换成 https

    // 使用POST方法  
     HttpMethod method = new PostMethod("http://www.7y8.com/V/ip.asp");  
    client.executeMethod(method);  
    // 打印服务器返回的状态  
    System.out.println(method.getStatusLine());  

    // 打印返回的信息  
    //String result = method.getResponseBodyAsString();  
    StringBuffer rets = new StringBuffer();
    InputStream responseBody = method.getResponseBodyAsStream();
    InputStreamReader in = new InputStreamReader(responseBody, "gb2312");
    BufferedReader br = new BufferedReader(in);
    String s = "";
    while ((s = br.readLine()) != null) {
        rets.append(s + "\n");
    }

    s = "";
    if (rets.toString().contains(host)) {
        box = new MessageBox(shell, SWT.CENTER);
        box.setText("IP测试!");
        box.setMessage("代理IP可用");
        box.open();
    }else{
        box = new MessageBox(shell, SWT.CENTER);
        box.setText("IP测试!");
        box.setMessage("代理IP不可用");
        box.open();
    }
    br.close();
    in.close();
    writeToTXT("C:\\Documents and Settings\\Administrator\\桌面\\xxx.html",rets);
    // 释放连接  
    method.releaseConnection();  


}  

2010-4-11 1:19:19 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
信息: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
2010-4-11 1:19:19 org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
信息: Retrying request

上面程序可以简单判断一个代理IP是否可用,但是有一种代理IP无法响应会引发以下异常,并且程序主界面同时会无法响应,问下这种异常该如何处理,因为IP最后是传进来的,这段代码里的IP我只是测试用,所以如果遇到无法响应的情况就无法处理了,希望得到满意的答复,谢谢!

  • 写回答

1条回答 默认 最新

  • iteye_13460 2010-04-11 10:39
    关注

    [size=x-large][color=red]我看出你把你这个方法的异常都往被调用处抛,所以你在调用这个方法的地方,按如下这样来catch.[/color][/size]

    [code="java"] public static void testTEST(){
    try{
    test(host,port);
    }catch(ConnectException e){
    System.out.println("代理无法响应...");
    JOptionPane.showMessageDialog(null, "代理无法响应);
    }

    }[/code]
    

    [size=large][color=red]
    当然,你要明白,异常可以向外抛出,也可以在本方法内自已处理,根据需要来选择.
    希望对你有所帮助.....[/color][/size]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路