欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

rest的调用 java 示例代码【原创】

程序员文章站 2022-03-04 15:20:15
...
1. 服务端示例代码(如何搭建rest服务,请看上一篇)
@Service
@Path("/msMqMessage")
public class MsMqServiceImpl implements MsMqService{	
	@Resource
	private MsMqUtil msMqUtil;
	
	@POST  
         @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	@Produces(MediaType.APPLICATION_JSON)  
	public void send(@FormParam("label") String label, @FormParam("body") String body){
		msMqUtil.send(label, body);
	}
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public List<Map<String, String>> receive(@QueryParam("count") int count)
	        throws java.io.UnsupportedEncodingException{
		return msMqUtil.receive(count);
	}
	
	public MsMqUtil getMsMqUtil() {
		return msMqUtil;
	}

	public void setMsMqUtil(MsMqUtil msMqUtil) {
		this.msMqUtil = msMqUtil;
	}
}


2. 客户端调用代码
public class RestClient {
	private static void post() {
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target("http://localhost:8080/cbec-msmq/msMqMessage");
		Form form=new Form();
		form.param("label", "123123");
		form.param("body", "hello");
		Response response = target.request().post(Entity.form(form));
		response.close();
	}
	
	private static void get(){
		Client client = ClientBuilder.newClient();
		WebTarget target = client.target("http://localhost:8080/cbec-msmq/msMqMessage")
				.queryParam("count", 1);
		Response response = target.request().get();
		System.out.println(response.readEntity(String.class));
	}
	
	public static void main(String[] args){
		post();
		get();
	}
}