繁体   English   中英

HTTPClient StringEntity PUT麻烦

[英]HTTPClient StringEntity PUT troubles

我正在努力通过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());
        }

我试过既设置内容类型又不设置内容类型,没有区别。 我做错了什么基本的事情?

事实证明,Base64.encodeBase64String在字符串的末尾添加了换行符,这一切都丢掉了!

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

哇,这花了我几天的时间才弄清楚!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM