resetful技术应用框架

resetful的post

   

   请求发送框架:restlet

   XML与Java对象绑定:XStream

	String root="http://10.103.124.169:8182/SVC/Basic";
		String methodName="getCustomerByUid";
		String system="cbd";
		String uid="8aedgagh";
		String uri=root+"/"+methodName+"/"+system+"/"+uid;
		ClientResource cr=new ClientResource(uri);		
		Representation r=cr.get();
		//返回结果,结果是一个MessageDto转换成的xml
		String result=r.getText();
		//把结果转成Object
		XStream xs=new XStream();
		MessageDto md=(MessageDto) xs.fromXML(result);
		SvcPcAllInfoDto spid=(SvcPcAllInfoDto)md.getObject();

     

   请求发送框架:httpclient

   XML与Java对象绑定:smooks

		PostMethod method = new PostMethod(postUrl);
		//由于请求的XML数据,所以需要添加内容格式类型
		method.setRequestHeader("Content-Type", XML_CONTENT_TYPE);
		
		method.setRequestEntity(new StringRequestEntity(strXml));
		log.debug(".................postmethod=" + method.toString());
		String response = exeMethod(method);
		
        //如果第一次不成功,则继续执行一次
        if (responseCheck(response)) {
		    method = new PostMethod(acpUrl + url);
		    method.setRequestHeader("Content-Type", XML_CONTENT_TYPE);
		    
		    log.debug(".................other postmethod=" + method.toString());
		    method.setRequestEntity(new StringRequestEntity(strXml));
		    response = exeMethod(method);
		    
		    //如果第二次不成功,则抛出异常
            responseError(response);
		}

    

	/**
	 * 通用方法执行处理,需要带上Cookie信息一起发送请求,并返回指定格式的响应信息。
	 * 
	 * @param method -- Get或Post请求方法
	 * @return 缺省返回XML格式的数据
	 * @throws AccessException
	 */
	private static String exeMethod(HttpMethodBase method)
			throws AccessException {
	    //log.debug(".............current charset: " + Charset.defaultCharset().toString());
		if (method == null) {
			throw new AccessException("请求方法对象为空!");
		}
        log.debug("VOS CURRENT USER CODE: " + UserCookieData.getUserName() + "; VOS CURRENT SESSION ID: " + UserCookieData.getSessionId());

		String responseText = "";
		String methodName = method.getName().toUpperCase();

		HttpClient client = new HttpClient();
		//设置 HttpClient 接收 Cookie,用与浏览器一样的策略
		client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		//设置发送请求内容的字符集
		client.getParams().setHttpElementCharset(SERVICE_CHARSET);
		client.getParams().setContentCharset(SERVICE_CHARSET);
		try {
			//检查是否有当前请求的Cookie,如有则添加一起发送请求
			setHttpCookie(method);

			long startTime = (new Date()).getTime();
			log.debug("exeMethod start time");

			int statusCode = client.executeMethod(method);
			log.debug(methodName + " Response Code: " + method.getStatusLine().toString());

			if (statusCode < 200 || statusCode >= 300) {
				//throw new AccessException(methodName + "请求失败,响应代号为:" + statusCode);
			    log.error(methodName + "请求失败,响应代号为:" + statusCode + ",将重新处理!");
			    return HTTPERROR;
			}
			
			//取返回字符串
			responseText = getReponseText(method).trim();

			//检查是否包含登陆信息,如果有则重新登录发送请求。
            //这种方案保证在长时间没访问ACP系统时,调用接口时找不到会话的问题
			if (responseText.indexOf("function login()") >= 0) {
			    return NOLOGIN;
			} else {
				long useTime = (new Date()).getTime() - startTime;
				log.debug("exeMethod use time:" + useTime);
				if (useTime > 2000) {
				    log.error("exeMethod use time:" + useTime + "; url:" + method.getURI());
				}
				//只显示最后200个字符
				int len = responseText.length(), start = len > 200 ? len - 200 : 0;
				log.debug(methodName + " Response Body: \n..." + responseText.substring(start, len));
			}
		} catch (HttpException e) {
			throw new AccessException(methodName + "请求失败:" + e.getMessage());
		} catch (IOException e) {
			throw new AccessException(methodName + "请求失败:" + e.getMessage());
		} finally {
			method.releaseConnection();
		}

		return responseText;
	}

 

 


    /**
     * 解析请求方法的返回信息为字符串
     * @param method -- 请求方法
     * @return
     * @throws AccessException
     */
    private static String getReponseText(HttpMethodBase method) throws AccessException {
        String responseText = "";
        
        InputStream response = null;
        try {
            response = method.getResponseBodyAsStream();

            byte[] bytes = StreamUtil.readStream(response);
            
            responseText = new String(bytes, method.getResponseCharSet());
        } catch (Exception e) {
            throw new AccessException(e);
        } finally {
            if (response != null) {
                try {
                    response.close(); response = null;
                } catch (IOException e) {
                    throw new AccessException(e);
                }
            }
        }
        
        return responseText;
    }

 

    public static  T xml2Java(Class entityClass, String xmlString) throws AccessException {
        T result = null;
        Smooks smooks = null;
        try {
            long startTime = (new Date()).getTime();
            String className = entityClass.getSimpleName();
            String configName = className.toLowerCase() + "-config.xml";
            
            // 加载smooks的配置文件
            smooks = new Smooks(entityClass.getResourceAsStream("/smooks/" + configName));

            JavaResult javaResult = new JavaResult();
            
            //必须根据客户端字符集获取字节流,否则中文值会是乱码
            ByteArrayInputStream ins = new ByteArrayInputStream(xmlString.getBytes(clientCharset));
            
            // 解析xml数据文件
            smooks.filterSource(new StreamSource(ins), javaResult);

            // 读取转换后的对象
            result = javaResult.getBean(entityClass);
            
            long useTime = (new Date()).getTime() - startTime;
            String info = "xml2Java " + className + " use time:" + useTime;
            log.debug(info);
            if (useTime > 500) log.error(info);
        } catch (IOException e) {
            throw new AccessException(e);
        } catch (SAXException e) {
            throw new AccessException(e);
        } catch (Exception e) {
            throw new AccessException(e);
        } finally {
            if (smooks != null) {
                smooks.close();
                smooks = null;
            }
        }

        return result;
    }

 

    

 
   

 

你可能感兴趣的:(企业级问题解决方案,java通讯)