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 回答