grails发送POST请求,接受请求

grails发送POST请求,接受请求
//此连接地址为配置到app-config.properties下面

def http = new HTTPBuilder(ConfigurationHolder.config.entrust.serverUrl)

//----发送请求 

/**
   *发送请求 ,参数根据具体接口内容拟定

   * @param orders 订单号集合,必须参数
   * @param auditor 审核人  必须参数
   * @return {result: 'true or false', errorMsg: '错误信息'}
   * result: true为成功, false 为失败,
   * errorMsg: 当result为false时,返回误原因,
   * @throws Exception
   */
  def refuseCheckForEntrust(orders,auditor) throws Exception {
    http.request(POST, JSON) { req ->
      uri.path = 'yourControllerName/yourMethodName'
      body = [orders:orders,auditor:auditor] //传递的参数,将要按照你所指定的格式进行发送
       req.getParams().setParameter("http.connection.timeout", new Integer(60000));
req.getParams().setParameter("http.socket.timeout", new Integer(60000));
      response.success = { resp, json ->
        return json
      }
      response.failure = { resp ->
        throw new Exception('发送POST请求失败"+resp)
      }
    }
  }

//---接受POST请求端解析,(以grails的controller为例,JAVA端的Action类似)

//1、第一种方式按照JAVA中的JSON-LIB方式转换为对象

           String jsonStr = request.JSON;//此处可以弱引用声明
            log.info 'process charge .'
            Charge charge = new Charge()
            charge = (Charge) JSONObject.toBean(JSONObject.fromObject(jsonStr), Charge.class);

//第二种方式按照grails弱引用的特点去取单独的某个参数

def jsonReq = request.JSON;//此处可以弱引用声明
def name = jsonReq.name

String jsonStr = jsonReq as String 

//返回请求端内容

def result = [result: false, errorMsg: "该账号已经存在,请重新输入"]
 render result as JSON


你可能感兴趣的:(grails)