如何使用XML执行HTTPPUT请求?

时间:2015-06-19 09:27:16

标签: java apache http-put

我正在学习rest API,我觉得很难做[{"a": 1, "city" : "p"}, {"b": 2, "city" : "a"}] 请求。下面是我试过的代码。但记录没有成功更新

使用的网址 - PUT

尝试更新的价值 - http://www.thomas-bayer.com/sqlrest/PRODUCT/1

语言:Java

<PRICE>24.8</PRICE> to <PRICE>24.9</PRICE>

我收到DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPut putrequest = new HttpPut( "http://www.thomas-bayer.com/sqlrest/PRODUCT/1"); List<NameValuePair> nvps = new ArrayList<NameValuePair>() {{ add(new BasicNameValuePair("content-type", "application/xml")); add(new BasicNameValuePair("Server", "Apache-Coyote/1.1")); }}; for (NameValuePair h : nvps) { putrequest.addHeader(h.getName(), h.getValue()); } String xml="<?xml version=\"1.0\"?><PRODUCT xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n" + " <ID>1</ID>\n" + " <NAME>Chair Shoe</NAME>\n" + " <PRICE>24.9</PRICE>\n" + "</PRODUCT>"; putrequest.setEntity(new StringEntity(xml)); HttpResponse response = httpClient.execute(putrequest); if (response.getStatusLine().getStatusCode() != 201) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } httpClient.getConnectionManager().shutdown(); } 响应,但如果使用500的记录不存在,我可以添加记录。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

如果它被添加并且你仍然得到500,那么有以下可能性:

  1. 添加记录后服务器遇到错误
  2. 服务器端代码错误地输入STATUS代码