HTTPURLConnection int responseCode = connection.getResponseCode();返回-1

时间:2018-09-17 08:04:03

标签: java http

在下面的代码中,运行hConn.disconnect();。我以为responseCode得-1。我该如何纠正? setRequestMethod("GET")是否必要?

public static void downloadFile(String fileURL, String saveDirectory)
            throws IOException {
        URL u = new URL(fileURL);
        HttpURLConnection hConn = (HttpURLConnection) u.openConnection();
        int responseCode = hConn.getResponseCode();


        if (responseCode == HttpURLConnection.HTTP_OK) {
           //some code here
           //some codes here
        } else {
            System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        }
        hConn.disconnect();
    }

0 个答案:

没有答案