搜索

首页  >  问答  >  正文

java - URL类里面的方法openConnection方法报错

我按照教程来却发现总是报错;
代码如下
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]
PHPzPHPz2904 天前419

全部回复(4)我来回复

  • 天蓬老师

    天蓬老师2017-04-18 10:31:37

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

    回复
    0
  • 高洛峰

    高洛峰2017-04-18 10:31:37

    httpUrl前面为什么有new

    回复
    0
  • 黄舟

    黄舟2017-04-18 10:31:37

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

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

    回复
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:31:37

    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,否则以后你的代码搞到生产环境,运维全靠心灵感应了,不是被人骂死。

    回复
    0
  • 取消回复