简体   繁体   中英

HTTPClient StringEntity PUT troubles

I am struggling with creating a plain text file on a server via HTTP PUT. I am using apache commons httpClient. My credentials are working but there is no body content in my request. What must I do to create the file like this? It works as intended when I try via hurl.it (ie setting my credentials, and setting a body). What I would like is the string "hej" to show in the file body. After getting this to work I intend to use a JSONString. The following code generates an empty file on the server (204 response):

        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());
        }

I have tried both setting a content type and not doing it, no difference. What basic thing am I doing wrong?

Turns out that Base64.encodeBase64String appends a newline character at the end of the string, which throws everything off!

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

Wow, that just took me a couple of days to figure out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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