当相同的URL在浏览器上工作时,HttpURLConnection将返回404状态代码

时间:2017-03-06 08:22:36

标签: java httpurlconnection

我通过从java代码更改一个参数向for循环中的URL发送GET请求。现在我的请求工作正常5-6次但是在某一点之后我的连接的状态代码变为404并且从那一点开始我的请求一直失败。但是当我尝试从浏览器连接到URL并遵循站点方向(单击使我访问相同URL的按钮)时,它没有任何问题。

以下是我用于Httpconnection的功能:

private static void getFile(String name) throws MalformedURLException, InterruptedException, UnsupportedEncodingException{
    String url = "http://<this is not showed>"+URLEncoder.encode(name.trim(),"UTF-8")+".mp3";
    URL obj = new URL (url);
        try {
            HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", USER_AGENT);
            connection.setDoOutput(true);
            connection.connect();
            //saving the file returned from request
            FileOutputStream fileOutputStream = new FileOutputStream(new File(System.getProperty("user.dir") + "/audios/"+name+".mp3"));
            InputStream inputStream = connection.getInputStream();
            byte[] buffer = new byte[1024];
            int len1 = 0;

            while((len1 = inputStream.read(buffer)) > 0){
                fileOutputStream.write(buffer, 0, len1);
            }

            fileOutputStream.close();
            connection.disconnect();
            break;

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

以下是我使用getFile功能的部分:

for (int i = 0; i < length; i++) {
            getFile(names[i]);
}

以下是循环的输出:

HTML connection status: 200
a| File downloaded succesfully.
HTML connection status: 200
 ab| File downloaded succesfully.
HTML connection status: 200
 ba| File downloaded succesfully.
HTML connection status: 200
 dî| File downloaded succesfully.
HTML connection status: 200
 jur| File downloaded succesfully.
HTML connection status: 200
 küs| File downloaded succesfully.
HTML connection status: 200
 ban| File downloaded succesfully.
HTML connection status: 404
java.io.FileNotFoundException:

它就像那样。

0 个答案:

没有答案