java - URL类里面的方法openConnection方法报错
PHPz
PHPz 2017-04-18 10:29:37
[Java讨论组]

我按照教程来却发现总是报错;
代码如下
private String url; //请求的地址

public httpThread(String url) {
    this.url = url;
}
public String doGet() {
    URL httpUrl = null;
    try {
        httpUrl = new URL(url);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpURLConnection httpURLConnection;
    httpURLConnection = (HttpURLConnection) new httpUrl.openConnection();
    try {
        httpURLConnection.setRequestMethod("GET");      //请求get方法
    } catch (ProtocolException e) {
        e.printStackTrace();
    }
    httpURLConnection.setReadTimeout(5000);
    //接受返回来的数据
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    String str;
    StringBuffer sb = new StringBuffer();
    try {
        while ((str = reader.readLine()) != null) {
            sb.append(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sb.toString();
}
![图片描述][2]
PHPz
PHPz

学习是最好的投资!

全部回复(4)
天蓬老师

请问 这是什么教程?使用浏览器看看请求是否管用 有可能作者编写时可以访问但是后来不能了

高洛峰

httpUrl前面为什么有new

黄舟
    public URLConnection openConnection() throws java.io.IOException {
        return handler.openConnection(this);
    }

这就是个方法你把new去掉啊

天蓬老师
URL httpUrl = null;
HttpURLConnection httpURLConnection;
try {
    httpUrl = new URL(url);
    httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
    httpURLConnection.setRequestMethod("GET");      //请求get方法
    httpURLConnection.setReadTimeout(5000);
} catch (MalformedURLException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (ProtocolException e) {
    e.printStackTrace();
}

前几句一直到"//接受返回来的数据"之前改成上面的再看看
两个问题,其一,调用方法前面为什么加个new,你要日天吗,ide报的错,鼠标移上去或者光标放上去Ctrl+F1好好看看是什么内容,大部分情况都可以看到原因
其二,try代码块外面的变量初始为null,在try里赋值,catch代码块又没有妥善处理异常,只是用printStackTrace打一下异常,那你后面调用这个引用变量的方法时,会有报NullPointException的情况,说的就是httpUrl这个对象,要么把那几句写到try里,出错就别运行,要吗在外面调用时候先验证是不是null,总之这里异常处理的不好,新手学习一定要好好学习妥善处理好异常,和你写注释一样养成良好的习惯,你后面的代码我都没再改了,另外我也没写处理的代码,但思路就是这样,不要printStackTrace了事,该log的log,该throw的throw,否则以后你的代码搞到生产环境,运维全靠心灵感应了,不是被人骂死。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号