1.服务端
package com.knife.test;
public class A {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "i am " + name + ", i " + age;
}
}
@RequestMapping("/testa")
@ResponseBody
public A testa(@RequestBody A a) {
Logger log = Logger.getLogger(getClass());
log.info(a);
return a;
}
2.客户端
String url="http://localhost:8081/testa";
//String entityJson="{\"name\":\"tom\",\"age\":1}";
A a=new A();
a.setName("knife");
a.setAge(100);
String entityJson=JSONObject.fromObject(a).toString();
HttpPost httpost = new HttpPost(url); // 设置响应头信息
httpost.addHeader("Content-Type", "application/json; charset=UTF-8");
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000)
.setConnectTimeout(3000).build();
httpost.setConfig(requestConfig);
httpost.setEntity(new StringEntity(entityJson, "UTF-8"));
String returnStr = null;
try {
HttpResponse response = HttpClientBuilder.create().build().execute(httpost);
returnStr = EntityUtils.toString(response.getEntity(), "utf-8");
Logger log=Logger.getLogger(testhttp.class);
log.info("message:"+returnStr);
} catch (Exception e) {
} finally {
httpost.releaseConnection();
}
14:17:57.668 [main] INFO com.knife.test.testhttp - message:{"name":"knife","age":100}
3.curl方式
[root@localhost ~]# curl -l -H "Content-type:applicate":"knife","age":100}' http://192.168.0.103:8081/testa
{"name":"knife","age":100}