REST,HTTP POST demo


客户端程序(其中,content为要传输的json数据):

                HttpPost httppost = new HttpPost(
				"http://xxxhost/api/my_path?mc=1");
		HttpClient httpclient = HttpClientBuilder.create().build();
		try {
			StringEntity reqEntity = new StringEntity(<strong><span style="color:#ff0000;">content</span></strong>);
			reqEntity.setContentType("application/json");
			httppost.setEntity(reqEntity);
			HttpResponse httpresponse = httpclient.execute(httppost);
			HttpEntity entity = httpresponse.getEntity();
			String body = EntityUtils.toString(entity);
			
			System.out.println(body);

服务器端程序:

@Path("/<span style="font-family: Arial, Helvetica, sans-serif;">my_path</span>")

public class Events {
@POST
@Consumes(MediaType.APPLICATION_JSON)
	public Response addEvent(<strong><span style="color:#ff0000;">@QueryParam</span></strong>(ConfigItemConstants.CONFIG_ITEM_MC) String mc, Object eventStr){
		if(!GenericValidator.isNullOrBlank(mc) && !ConfigItemUtil.verifyMC(mc)){//在这里,验证你传过来的mc参数,通过则继续
			return ResponseUtil.setErrorResponse(403, "Forbidden", "User does not have access to this service!");
		}
		EventService eventService = new EventService();
		int code = 200;
		String resBody = "";
		int rtn = 0;
		try {
			Long id = eventService.createEvent(eventStr);//传过来的json数据都在eventStr中,你可以根据需求自己处理,比如存储到NoSQL中。
			rtn = 1;
		} catch (Exception e) {
			rtn = -1;
			e.printStackTrace();
		} 
		
		if(rtn == 1){
			code = 201;
			resBody = "The event created successfully";
		}else if(rtn == -1){
			code = 400;
			resBody = "Format of request is not correct";
		}
		
//		logger.exit();
		if(rtn == 1){
			return ResponseUtil.setResponse(code, resBody);
		} else {
			return ResponseUtil.setErrorResponse(code, "Bad Request", resBody);
		}
	}
	
	@Path("{delete}")
	@DELETE
	@Consumes(MediaType.APPLICATION_JSON)
	public Response deleteEvent(@QueryParam(ConfigItemConstants.CONFIG_ITEM_MC) String mc, String vehicleId){
		if(!GenericValidator.isNullOrBlank(mc) && !ConfigItemUtil.verifyMC(mc)){
			return ResponseUtil.setErrorResponse(403, "Forbidden", "User does not have access to this service!");
		}
		
		EventService eventService = new EventService();
		int code = 200;
		String resBody = "";
		int rtn = 0;
		try{
			Long id = eventService.deleteEvent(vehicleId);
			rtn = 1;
		}catch(Exception e){
			rtn = -1;
			e.printStackTrace();
		}
		if(rtn == 1){
			code = 201;
			resBody = "The event created successfully";
		}else if(rtn == -1){
			code = 400;
			resBody = "Format of request is not correct";
		}
		
		if(rtn == 1){
			return ResponseUtil.setResponse(code, resBody);
		} else {
			return ResponseUtil.setErrorResponse(code, "Bad Request", resBody);
		}
	}
	
	}

Note:客户端程序和服务器端程序只是相对来说的,这是受传统开发web project的思维影响!新的技术都可能颠覆这种思维!做技术,思维一定要跟上!尤其是出现了REST,DevOps,cloud service,Nodejs,distribution app。

准确来说一个是http post request端,一个是http post response端。实际上,这两个都是服务器容器App



你可能感兴趣的:(REST,HTTP POST demo)