`

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

 

    


 

分享到:
评论

相关推荐

    resetful所需jar包

    resetful所需jar包包含aop,beans,context,core,web五个jar包

    REST api架构

    SDK 博文链接:https://hudeyong926.iteye.com/blog/1829987

    yii2 resetful 授权验证详解

    主要介绍了yii2 resetful 授权验证详解,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    wapman:wapman -vue多页应用

    基于apicloud应用开发框架,结合现在最流行的vue前端框架,打造一个体验相对完美的手机app 这款应用是一套h5的代码适用ios,Android两个平台,而且可以在平台市场上架成功 适合人群 对node已经管理可以玩得转了,...

    motor:nodejs 服务端框架

    这是用nodejs写的一个web服务器框架 谈不上什么模式,不过其流程清晰、配置简单、操控性强。 ###motor特点 路由策略遵循resetful规范; 自带session管理,易扩展; 自带模板引擎,性能强悍,并提供使用模板引擎缓存...

    用python写restful接口

    使用python的第三方库编码写restful接口,easy

    osf-openstack-training-master.zip

    resetful接口服务的扩展 ###nova数据库调用接口服务的扩展 compute接口的扩展 keystone接口服务的扩展 基于openstack服务、配置架构自定义服务模块 ###Django快速入门 Demo for a "Hello World" Django ORM 介绍 ...

    php增删改查、支持批量操作、是我刚接触时花一天时间写的、很有成就感

    这是我在学校老师花了十分钟给我讲解php运行环境后,回来就写出来的一个练习,包括数据库连接、批量操作数据、前台后台一并、清楚,适合初学者,我花了一天,你看到了我写的源码可能会理解的更快,有些函数不明白的...

    restful API 介绍与规范

    restful API 介绍与规范

    blog3.0:博客V3.0当前使用的技术(Nuxtjs + Nestjs + Vue + Element ui + vuetify),存储(MongoDB + Redis + COS)

    不才的博客 :smiling_face_with_sunglasses:巩固知识、打发时间本项目基于... :speak-no-evil_monkey: (日常记性不行)细节方面展示 :alien_monster:技术栈博客有点为了堆技术栈而堆技术栈的感觉。原本是打算直接3n框

    RESTful API设计规范

    RESTful架构应该遵循统一接口原则,统一接口包含了一组受限的预定义的操作,不论什么样的资源,都是通过使用相同的接口进行资源的访问。... ...而GET、HEAD、PUT和DELETE请求都是幂等的,无论对资源操作多少次, 结果总是...

    用Node编写RESTful API接口的示例代码

    本篇文章主要介绍了用Node编写RESTful API接口的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    egg-demo:鸡蛋+ ts +猫鼬+宁静+ graphql +时间表演示

    Node 使用 Egg 框架 之 上TS 的教程(一) Node + Egg + TS + Mongodb + Resetful 作为一个从优美的、面向对象的、专业的:C、C++、C#、JAVA一路过来的程序员,开始让我写JS,我是拒绝的。这哪里是在写代码,明明是...

    RestfulAPI-s:使用最佳实践实现的RESTFul Web服务

    RestfulAPI-s:使用最佳实践实现的RESTFul Web服务

    微信小程序的后端Java Demo程序.rar

    后台resetful接口编写 小程序调用后台接口 免费的https申请 linux下部署上线 三、微信小程序项目构建 这些基础的东西我就不过多介绍,大家在刚开始开发的时候一般都没有自己的服务器及域名,所以大家在本地编写...

    RESTful-API-demo:RESTful API演示

    网络应用-重前端轻后端模式,后端专注于业务,提供前端数据接口。一套API给多客户端提供服务 Resetful API-设计更加规范的API RESTful(Representational State Transfer)-表现层状态转化 每一个URI代表一种资源。为...

    ansible-api:Ansible的RESTful HTTP Api

    是一个非常简单的IT自动化系统。 如果您要使用它而不是CLI,请立即尝试。...变更日志0.5.1 添加对签名的sha256加密支持(thx:jbackman) 适合最新的ansible(v2.8.6)和ansible-runner(v1.4.2) 作为响应添加更多...

    restletclient插件

    restletclient插件、该插件安装在chrome浏览器下。在chrome浏览器更多工具,扩展程序下面进行安装

Global site tag (gtag.js) - Google Analytics