java - URL类里面的方法openConnection方法报错
PHPz
PHPz 2017-04-18 10:29:37
0
4
417

我按照教程来却发现总是报错;
代码如下
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)
Peter_Zhu

請問 這是什麼教學?使用瀏覽器看看請求是否管用 有可能作者編寫時可以訪問但是後來不能了

小葫芦

httpUrl前面為什麼有new

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

這就是一個方法你把new去掉啊

Peter_Zhu
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,否則以後你的程式碼搞到生產環境,運維全靠心靈感應了,不是被人罵死。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板