我需要将数据从独立客户端推送回服务器。这个客户端已经访问服务器以获取信息,解析它,执行它必须做的事情,但现在我需要它来推回一些信息。
我试过这样做:
public class UpdateServer {
public void update(int resultSetRowCount) {
AgentConfiguration config = new AgentConfiguration();
config.init();
String agentId = AgentConfiguration.agent_id;
String serverIp = AgentConfiguration.server_ip;
String serverPort = AgentConfiguration.server_port;
Calendar cal = Calendar.getInstance();
StringBuilder timestamp = new StringBuilder();
timestamp.append(cal.get(Calendar.YEAR));
timestamp.append(String.format("%02d",cal.get(Calendar.MONTH) + 1));
timestamp.append(String.format("%02d",cal.get(Calendar.DAY_OF_MONTH)));
timestamp.append(String.format("%02d",cal.get(Calendar.HOUR_OF_DAY)));
timestamp.append(String.format("%02d",cal.get(Calendar.MINUTE)));
timestamp.append(String.format("%02d",cal.get(Calendar.SECOND)));
String date = timestamp.toString();
String uri = "http://" + serverIp + ":" + serverPort + "/hrm/alerts/" + agentId + "/" + date + "/" + resultSetRowCount;
System.out.println(uri);
try {
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
// Create new patchRequest with below mentioned URL
HttpPost postRequest = new HttpPost(uri);
// Add additional header to postRequest which accepts application/xml data
postRequest.addHeader("accept", "application/xml");
// Execute your request and catch response
HttpResponse response = httpClient.execute(postRequest);
// Check for HTTP response code: 200 = success
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
我尝试使用格式化的uri访问服务器:
new UpdateServer().update(resultSetRowCount);
但我得到以下例外:
Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 405
我在这里缺少什么?
答案 0 :(得分:1)
http错误代码405的原因之一是有效负载未传递给POST方法。您的计划可能就是这种情况。
您可以使用PostMethod
代替HttpPost
并设置有效负载
您的代码看起来像
...
String uri = "http://" + serverIp + ":" + serverPort + "/hrm/alerts/" + agentId + "/" + date + "/" + resultSetRowCount;
System.out.println(uri);
try
{
// create HTTP Client
HttpClient httpClient = HttpClientBuilder.create().build();
PostMethod post = new PostMethod(uri);
RequestEntity requestEntity = new StringRequestEntity(payload, "application/xml", null/*charset default*/);
post.setRequestEntity(requestEntity);
int iResult = httpclient.executeMethod(post);
// get the status code using post.getStatusCode()
// you can get the response using post.getResponseBodyAsString()
// Check for HTTP response code: 200 = success
if (post.getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + post.getStatusCode());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}