2

私は、URL に空のスペースが含まれる場合があるプロジェクトに取り組んでいます (常にではありません)。

私のコード:

     try {
            URL url = new URL(stringURL);
            URLConnection conexion = url.openConnection();
            conexion.connect();

            // downlod the file
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            OutputStream output = new FileOutputStream(fullPath.toString());

            byte data[] = new byte[1024];

            while ((count = input.read(data)) != -1) {
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

失敗するのは次の行です: InputStream input = new BufferedInputStream(url.openStream(), 8192);

a: java.io.FileNotFoundException.

特定の行をエンコードしようとしましたが、キッカーは次のとおりです。サーバーはファイルを見つけるために空のスペース " " を必要とするため、何らかの形で空のスペースが必要です。Firefox ブラウザーを使用すると、ファイル (jpg) を見つけることができます。どんな助けでも大歓迎です。

編集の更新:さて、URL のホスト部分の後のすべてのビットを utf-8 にエンコードしようとしました。空白には + と %20 の両方を使用してみました。これでファイルを DL できますが、ファイルに問題があるため読み取ることができません。

update2 の編集: %20 で間違いを犯しましたが、動作します。

4

1 に答える 1

2

さて、私は頭痛を解決しました。

最初に使用します:

completeUrl.add(URLEncoder.encode(finalSeperated[i], "UTF-8"));

「/」の間の URL のすべての部分

それから私は使用します:

    ArrayList<String> completeUrlFix = new ArrayList<String>();
    StringBuilder newUrl = new StringBuilder();
    for(String string : completeUrl) {
        if(string.contains("+")) {
            String newString = string.replace("+", "%20");
            completeUrlFix.add(newString);
        } else {
            completeUrlFix.add(string);
        }
    }

    for(String string : completeUrlFix) {
        newUrl.append(string);
    }

適切な urlString を構築するには。

これが機能する理由は、http が %20 を必要とするためです。PowerlordによるJavaコメントのトラブルパーセントエンコーディングスペースを参照してください

于 2011-11-02T19:49:56.517 に答える