restEasy接受http請求的三種方式

配置類的訪問路徑:

@Path(GlobalConstants.DBPROXY_SERVER_CONTEXT + "/" + Version._1 + "/attachment")


配置方法的訪問路徑:

獲取get請求:

返回給客戶端的是json類型

@Path("/get/{ID}")
@GET
@Produces("application/json")
public ServerResponse getAttachment(@PathParam(value = "ID") String ID)

獲取post請求

@POST

public ServerResponse getAttachment(@FormParam(value = "ID") String ID)

獲取put傳輸的文件:

@Context
使用@Context可以獲取HttpServletRequest,HttpServletResponse。

@Path("/newAttach/{ID}")
	@PUT
	@Produces("application/json")
	public ServerResponse newAttach(@PathParam("ID") String ID,@Context HttpServletRequest request) throws IOException{
		Long requestTime = System.currentTimeMillis();
		logger.info("@GET " + requestTime + " AttachmentResource.newAttach ID:" + ID );
		ServerResponse sr = null;
		InputStream in = null;
		try {
			
			in = request.getInputStream();
			byte[] data = IOUtil.read(in);
			AttachmentHelper.newAttach(ID,data);
			sr = new ServerResponse("{\"isSuccess\":\"true\"}");
		} catch (EOPException e) {
			e.printStackTrace();
			logger.error("EXCEPTION:" + e.getExceptionCode() + " CODE:" + e.getExceptionCode().getCode() + " MESSAGE:" + e.getMessage(), e);
			sr = new ServerResponse(e.getMessage(), e.getExceptionCode());
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			sr = new ServerResponse(e.getMessage(), ExceptionCode.DBPROXY_OTHER);
		}
		logger.info("@GET " + requestTime + " ServerResponse.newAttach sr:" + sr.toString() + " use:" + (requestTime - System.currentTimeMillis()));
		return sr;
	}

resteasy返回響應文件,在produces裏可以寫("*/*")可以表示任意文件,使用@context註解獲取response。

@Path("/getAttach/{ID}")
	@GET
	@Produces("*/*")
	public ServerResponse getAttach(@PathParam("ID") String ID,@Context HttpServletResponse response){
		Long requestTime = System.currentTimeMillis();
		logger.info("@GET " + requestTime + " AttachmentResource.getAttach ID:" + ID );
		OutputStream outputStream = null;
		ServerResponse sr = null;
		byte[] data = null;
		try {
			outputStream = response.getOutputStream();
			data  = AttachmentHelper.getAttach(ID);
			outputStream.write(data);
			outputStream.flush();
			outputStream.close();
		} catch (EOPException e) {
			e.printStackTrace();
			logger.error("EXCEPTION:" + e.getExceptionCode() + " CODE:" + e.getExceptionCode().getCode() + " MESSAGE:" + e.getMessage(), e);
			sr = new ServerResponse(e.getMessage(), e.getExceptionCode());
		}catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			sr = new ServerResponse(e.getMessage(), ExceptionCode.DBPROXY_OTHER);
		}
		logger.info("@GET " + requestTime + " ServerResponse.getAttach sr:" + sr.toString() + " use:" + (requestTime - System.currentTimeMillis()));
		return sr;
	}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章