论坛首页 综合技术论坛

resetful技术应用框架

浏览 4592 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2013-04-24  

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();

     

   请求发送框架:restlet

   XML与Java对象绑定:XStream

		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);
		}

    

    public static <T> T xml2Java(Class<T> 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;
    }

 

    

	/**
	 * 通用方法执行处理,需要带上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;
	}

 

   发表时间:2013-04-26  
//如果第一次不成功,则继续执行一次 
。。。。。。。。

看到这段代码,很有意思,能告诉我为什么吗?
0 请登录后投票
   发表时间:2013-04-27   最后修改:2013-11-25
0 请登录后投票
   发表时间:2013-04-28  
是restful 
不是resetful
0 请登录后投票
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics