我正在努力通过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());
}
我尝试过设置内容类型而不是这样做,没有区别。我做错了什么基本的事情?
答案 0 :(得分:1)
事实证明,Base64.encodeBase64String在字符串末尾附加一个换行符,这会抛出一切!
String encoding = http_username + ":" + http_password;
encoding = Base64.encodeBase64String(encoding.getBytes());
encoding= encoding.replace("\r\n", ""); //This fixes everything
哇,我花了几天时间才想出来!