java 模拟请求@RequestBody

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}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值