2013-03-18 45 views
1

我很努力通过HTTP PUT在服务器上创建纯文本文件。我使用的是Apache Commons httpClient。我的凭据正在运行,但我的请求中没有正文内容。我必须做什么来创建这样的文件?当我通过hurl.it尝试(即设置我的凭证,并设置一个主体)时,它的工作方式与预期相同。我想要的是在文件正文中显示的字符串“hej”。得到这个工作后,我打算使用JSONString。下面的代码生成在服务器(204响应)的空的文件:HTTPClient StringEntity PUT麻烦

 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

您当前的代码根本没有发送文件,它会在请求正文中发送一些纯文本。什么是您的服务器端资源期望(如果您包括资源方法,它将帮助我们帮助您)。 – Perception 2013-03-18 18:14:44

+0

服务器端无法访问,所以无法提供有关它的更多信息。你可以在这里列出内容:http://upload.cmstest01.ku.dk/ data.json文件是由上面的代码生成的,而data2.json是在我通过hurl.it尝试时生成的。 – oskbor 2013-03-18 18:21:11

+2

不能给你建议不知道有效的请求应该是什么样子。但是,您可以做的是,打开Goog​​le Chrome开发者工具运行hurl.it测试,然后在网络选项卡中检查发送到服务器的所有HTTP属性。然后在客户端代码中复制这些设置。如果您需要帮助,请将您发现的财产信息发布到您的问题中。 – Perception 2013-03-18 18:24:28

回答

1

原来,Base64.encodeBase64String在字符串的末尾附加了一个换行符,它会抛出所有的东西!

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

哇,这只是花了我几天才弄清楚!