1.客户端实现
导入http-client jar。
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
public static void clientDemo() {
try {
String requestUrl = "http://hello/demo";
PostMethod postMethod = new PostMethod(requestUrl);
String data = "json_json_json_json";
StringRequestEntity stringRequestEntity = new StringRequestEntity(data, "application/x-www-form-urlencoded", "utf-8");
postMethod.setRequestEntity(stringRequestEntity);
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
//调用接口
int code = httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
System.out.println("接口状态" + code);
System.out.println("响应" + result);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
2.服务端实现
@RequestMapping(value = "/receive", method = RequestMethod.POST)
@ResponseBody
public String receiveFare(@RequestBody String str) {
System.out.println("接到数据:" + str);
return "ok";
}