1

HTTP PUT を介してサーバー上にプレーン テキスト ファイルを作成するのに苦労しています。私はApache Commons httpClientを使用しています。資格情報は機能していますが、リクエストに本文コンテンツがありません。このようなファイルを作成するにはどうすればよいですか? hurl.it を介して試してみると、意図したとおりに動作します (つまり、資格情報の設定と本文の設定)。私が望むのは、ファイル本体に表示する文字列「hej」です。これを機能させた後、JSONString を使用するつもりです。次のコードは、サーバー上に空のファイルを生成します (204 応答)。

        HttpClient httpClient = new DefaultHttpClient();

        String encoding = http_username + ":" + http_password;
        encoding = Base64.encodeBase64String(encoding.getBytes());
        HttpPut httpput = new HttpPut(http_path);

        HttpEntity content=null;
        try{
         content = new StringEntity("hej");
        }
        catch(UnsupportedEncodingException e){
            logger.error("Failed to Encode result");
        }


        logger.info("executing request " + httpput.getRequestLine());
        try {
            httpput.setHeader("Authorization", "Basic " + encoding);
            //httpput.setHeader("Content-Type", "application/json; charset=utf-8");
            httpput.setEntity(content);
            HttpResponse response = httpClient.execute(httpput);
            Header[] allHeaders = response.getAllHeaders();
            for (Header h : allHeaders) {
                logger.info(h.getName() + ": " + h.getValue());
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }

コンテンツタイプを設定することとしないことの両方を試しましたが、違いはありません。私が間違っている基本的なことは何ですか?

4

1 に答える 1

1

Base64.encodeBase64String が文字列の最後に改行文字を追加し、すべてが台無しになることがわかりました!

String encoding = http_username + ":" + http_password;
encoding = Base64.encodeBase64String(encoding.getBytes());
encoding= encoding.replace("\r\n", ""); //This fixes everything

うわー、それを理解するのに数日かかりました!

于 2013-03-21T17:27:21.570 に答える