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

阅读更多
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> 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();
	}
}

你可能感兴趣的:(rest,client,jersey,post)