zoukankan      html  css  js  c++  java
  • webservice_rest接口_学习笔记

    1、声明WebClientUtil工具类

    public class WebClientUtil {
    public static String doPost(String url,Map<String, Object> params,String token,String contentType,int connectTimeout,int readTimeout,String dataType) throws Exception
    {
    System.out.println("调用:-" + url + "接口,参数列表:-" + params);
    String parameterData = null;
    OutputStream outputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    StringBuffer resultBuffer = new StringBuffer();
    String tempLine = null;
    if (params != null)
    {
    parameterData = "";
    if("json".equals(dataType)){
    parameterData = JSON.toJSONString(params);
    }else{
    for (String key : params.keySet()) {
    parameterData = parameterData + (parameterData.equals("") ? "" : "&") + key + "=" + URLEncoder.encode(String.valueOf(params.get(key)), "UTF8");
    }
    }
    }
    HttpURLConnection httpURLConnection = getHttpURLConn(url, parameterData,"POST",token,contentType,connectTimeout,readTimeout);
    if (parameterData != null)
    {
    outputStream = httpURLConnection.getOutputStream();
    outputStreamWriter = new OutputStreamWriter(outputStream);
    outputStreamWriter.write(parameterData.toString());
    outputStreamWriter.flush();
    }
    inputStream = httpURLConnection.getInputStream();
    inputStreamReader = new InputStreamReader(inputStream);
    reader = new BufferedReader(inputStreamReader);
    while ((tempLine = reader.readLine()) != null) {
    resultBuffer.append(tempLine);
    }
    closeStream(outputStream,outputStreamWriter,inputStream,inputStreamReader,reader);
    return resultBuffer.toString();
    }

    public static String doGet(String url, Map<String, Object> params,String token,String contentType,int connectTimeout,int readTimeout,String dataType) throws Exception
    {
    System.out.println("调用:-" + url + "接口,参数列表:-" + params);
    String parameterData = null;
    OutputStream outputStream = null;
    OutputStreamWriter outputStreamWriter = null;
    InputStream inputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    StringBuffer resultBuffer = new StringBuffer();
    String tempLine = null;
    if (params != null)
    {
    parameterData = "";
    if("json".equals(dataType)){
    parameterData = JSON.toJSONString(params);
    }else{
    for (String key : params.keySet()) {
    parameterData = parameterData + (parameterData.equals("") ? "" : "&") + key + "=" + URLEncoder.encode(String.valueOf(params.get(key)), "UTF8");
    }
    }
    }
    HttpURLConnection httpURLConnection = getHttpURLConn(url,parameterData, "GET",token,contentType,connectTimeout,readTimeout);
    inputStream = httpURLConnection.getInputStream();
    inputStreamReader = new InputStreamReader(inputStream);
    reader = new BufferedReader(inputStreamReader);
    while ((tempLine = reader.readLine()) != null) {
    resultBuffer.append(tempLine);
    }
    closeStream(outputStream, outputStreamWriter, inputStream, inputStreamReader, reader);
    return resultBuffer.toString();
    }

    private static HttpURLConnection getHttpURLConn(String url, String parameterData,String mode,String token,String contentType,int connectTimeout,int readTimeout)
    throws MalformedURLException, IOException, ProtocolException
    {
    URL localURL = new URL(url);
    if("GET".equals(mode)){
    localURL = new URL(url+"?"+parameterData);
    }
    URLConnection connection = localURL.openConnection();
    HttpURLConnection httpURLConnection = (HttpURLConnection)connection;
    httpURLConnection.setDoOutput(true);
    if(connectTimeout > 0){
    httpURLConnection.setConnectTimeout(connectTimeout);//设置连接超时
    }
    if(readTimeout > 0){
    httpURLConnection.setReadTimeout(readTimeout);//设置读取超时
    }
    httpURLConnection.setRequestMethod(mode);
    httpURLConnection.setRequestProperty("Accept","*");
    httpURLConnection.setRequestProperty("connection","Keep-Alive");
    httpURLConnection.setRequestProperty("Accept-Charset","utf-8");
    if(StrUtil.isNotNull(contentType)){
    httpURLConnection.setRequestProperty("Content-Type",contentType);
    }else{
    httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    }
    if(StrUtil.isNotNull(token) && !"null".equals(token)){
    httpURLConnection.setRequestProperty("Authorization","Bearer "+token);
    }
    httpURLConnection.setRequestProperty("Content-Length",String.valueOf(parameterData == null ? 0 : parameterData.length()));
    //设置是否从httpUrlConnection读入,默认情况下是true;
    httpURLConnection.setDoInput(true);
    //Post 请求不能使用缓存
    httpURLConnection.setUseCaches(false);
    return httpURLConnection;
    }

    private static void closeStream(OutputStream outputStream, OutputStreamWriter outputStreamWriter, InputStream inputStream, InputStreamReader inputStreamReader, BufferedReader reader)
    {
    if (outputStreamWriter != null) {
    try
    {
    outputStreamWriter.close();
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    }
    if (outputStream != null) {
    try
    {
    outputStream.close();
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    }
    if (reader != null) {
    try
    {
    reader.close();
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    }
    if (inputStreamReader != null) {
    try
    {
    inputStreamReader.close();
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    }
    if (inputStream != null) {
    try
    {
    inputStream.close();
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }
    }
    }

    public static void main(String[] args) throws Exception{
    String url = "http://127.0.0.1:8080/rdpe-shanxi/rest/commonApiRestful.action";
    Map<String,Object> params = new HashMap<String,Object>();
    Map<String,Object> sss = new HashMap<String,Object>();
    Map<String,Object> bbb = new HashMap<String,Object>();
    bbb.put("identitycard","BMP20190515170343351");
    sss.put("action", "txMktSmsSend");
    sss.put("params",JSON.toJSONString(bbb));
    params.put("jsonStr",JSON.toJSONString(sss));
    System.out.println(WebClientUtil.doPost(url,params,"","",3000,3000,""));
    }

    public static String invokeQueryByBcapOpen(String requesturl,Map<String,Object> params,String requestmode,String contentType,String token,String dataType,int connectTimeout,int readTimeout) throws Exception {
    String resultJson="";
    if("GET".equals(requestmode)){
    resultJson = WebClientUtil.doGet(requesturl, params, token, contentType, connectTimeout, readTimeout, dataType);
    }else if("POST".equals(requestmode)){
    resultJson = WebClientUtil.doPost(requesturl, params, token, contentType, connectTimeout, readTimeout, dataType);
    }
    return resultJson;
    }

    2、声明接口调用类

    package com.bonc.business.restful;

    import java.lang.reflect.Method;
    import java.util.HashMap;
    import java.util.Map;

    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;

    import com.alibaba.fastjson.JSON;
    import com.bonc.business.db.F;
    import com.bonc.business.db.TxException;
    import com.bonc.business.entity.SysParam;
    import com.bonc.business.tools.ConfigUtil;
    import com.bonc.business.tools.Encypt;
    import com.bonc.business.tools.JsonBody;
    import com.bonc.business.tools.ParamVo;
    import com.bonc.business.tools.httpclient.WebClientUtil;
    import com.bonc.business.utils.Ajax;
    import com.bonc.business.utils.CST;
    import com.bonc.common.CrontabTask;


    /**
    *
    * ClassName: CommonApiRestFul <br/>
    * Function: 统一对外服务RestFul 接口. <br/>
    */
    @CrossOrigin
    @Controller
    @RequestMapping(value = "/rest")
    public class CommonApiRestFul {

    private static final boolean encyptbase64=Boolean.parseBoolean(ConfigUtil.getInstance().getValueByProperty(F.CfgFile, "encyptbase64"));

    private static final String url = ConfigUtil.getInstance().getValueByProperty(F.CfgFile, "market_helper.url");
    private static final String requestmode=ConfigUtil.getInstance().getValueByProperty(F.CfgFile, "market_helper.requestmode");
    private static final String contentType=ConfigUtil.getInstance().getValueByProperty(F.CfgFile, "market_helper.contentType");
    private static final String token="";
    private static final String dataType="json";
    private static final int connectTimeout=30000;
    private static final int readTimeout=30000;

    @ResponseBody
    @RequestMapping(value = "/commonApiRestful.action", method = RequestMethod.POST, produces = CST.PRODUCES_JSON)
    public Object commonApiRestful(HttpServletRequest request,String jsonStr,HttpServletResponse response) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    System.out.println(jsonStr);
    Map<String,Object> params = new HashMap<String,Object>();
    params.put("jsonStr",jsonStr);
    WebClientUtil wc = new WebClientUtil();
    String resultJsonStr = "";
    try {
    resultJsonStr = wc.invokeQueryByBcapOpen(url, params, requestmode, contentType, token, dataType, connectTimeout, readTimeout);
    } catch (Exception e) {
    e.printStackTrace();
    String code = CST.RES_EXCEPTION;
    String msg = "调用接口执行出错!"+e.getMessage();
    resultJsonStr = Ajax.responseString(code,msg,"",null);
    if(encyptbase64){
    resultJsonStr = Encypt.setEncString(resultJsonStr);
    }
    }
    return resultJsonStr;
    }

    }

    package com.bonc.business.restful;

    import java.lang.reflect.Method;
    import java.util.Map;

    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.lang.StringUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.CrossOrigin;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;

    import com.alibaba.fastjson.JSON;
    import com.bonc.business.db.F;
    import com.bonc.business.db.TxException;
    import com.bonc.business.entity.SysParam;
    import com.bonc.business.tools.ConfigUtil;
    import com.bonc.business.tools.Encypt;
    import com.bonc.business.tools.JsonBody;
    import com.bonc.business.tools.ParamVo;
    import com.bonc.business.utils.Ajax;
    import com.bonc.business.utils.CST;
    import com.bonc.common.CrontabTask;


    /**
    *
    * ClassName: CommonApiRestFul <br/>
    * Function: 统一对外服务RestFul 接口. <br/>
    */
    @CrossOrigin
    @Controller
    @RequestMapping(value = "/rest")
    public class CommonApiRestFul2 {
    /* @Resource
    private SystemConfigService systemConfigService;
    @Resource
    private BaseInterfaceLogService baseInterfaceLogService;
    @Resource
    private ExecutorAsynTaskService executorAsynTaskService;*/

    //是否开启传输数据过程中数据加密解密
    private static final boolean encyptbase64=Boolean.parseBoolean(ConfigUtil.getInstance().getValueByProperty(F.CfgFile, "encyptbase64"));
    //private static final boolean encyptbase64=false;

    @ResponseBody
    @RequestMapping(value = "/commonApiRestful2.action", method = RequestMethod.POST, produces = CST.PRODUCES_JSON)
    public Object commonApiRestful2(HttpServletRequest request,@RequestBody String jsonStr,HttpServletResponse response) {
    response.setHeader("Access-Control-Allow-Origin", "*");
    // JsonBody res = new JsonBody();
    String resultJsonStr="";
    String code=CST.RES_SECCESS;
    String msg="调用接口执行成功";
    Object obj=null;
    String interfacelogid = "";
    String resmethod = "";
    String resparams = "";
    String createStaff = "";
    System.out.println(jsonStr);
    boolean flag = true;
    try {
    if(StringUtils.isBlank(jsonStr)){
    code = CST.RES_EXCEPTION;
    msg = "不得传入空值参数jsonStr";
    flag = false;
    }
    if(flag){
    //将json参数转换成map
    Map<String, Object> requestform = JSON.parseObject(jsonStr, Map.class);
    if(encyptbase64){
    jsonStr = Encypt.setDesString(requestform.get("jsonStr")+"");
    }else{
    jsonStr = requestform.get("jsonStr")+"";
    }
    Map<String, Object> form = JSON.parseObject(jsonStr, Map.class);
    if(form.containsKey("action")){
    if(StringUtils.isBlank(form.get("action")+"")){
    code = CST.RES_EXCEPTION;
    msg = "接口的action参数不能为空";
    flag = false;
    }
    }else{
    code = CST.RES_EXCEPTION;
    msg = "传输的json格式参数无效,没有action";
    flag = false;
    }
    if(form.containsKey("params")){
    if(StringUtils.isBlank(form.get("params")+"")){
    code = CST.RES_EXCEPTION;
    msg = "接口的params参数不能为空";
    flag = false;
    }
    }else{
    code = CST.RES_EXCEPTION;
    msg = "传输的json格式参数无效,没有params";
    flag = false;
    }

    if(flag){
    resmethod = (String) form.get("action");
    resparams = form.containsKey("params")?form.get("params").toString():"";

    ParamVo vo = new ParamVo();
    vo.put("paramCode","interfaceconfig");
    vo.put("paramKey",form.get("action"));
    //SysParam sysParam = this.systemConfigService.getSysParaByUnionKey(vo);
    Object result = null;
    if(true){
    //校验传参是否有效
    //Map<String, Object> params = JSON.parseObject(form.get("params")+"", Map.class);

    /*if(params.containsKey("createStaff") || params.containsKey("userId") || params.containsKey("staffId")){
    if(StringUtils.isNotBlank(params.get("createStaff")+"")){
    createStaff = (String) params.get("createStaff");
    }else if(StringUtils.isNotBlank(params.get("userId")+"")){
    createStaff = (String) params.get("userId");
    }else if(StringUtils.isNotBlank(params.get("staffId")+"")){
    createStaff = (String) params.get("staffId");
    }
    }

    JsonBody check = new JsonBody(params);
    if(!check.isValid(sysParam.getParamExt1(),"{"alias":"1"}")){
    code = CST.RES_EXCEPTION;
    msg = (String) check.get("_invalidMessage");
    flag = false;
    }*/

    if(flag){
    //定义的service层处理方法类路径:
    //com.bonc.rdpe.service.BusiProcessMonitorService.getBusiProcessMonitorByParams
    String paramValue = "com.bonc.business.service.services.TriggerRestfulService.getTriggerInfoList";
    String[] splitstrs = paramValue.split("\.");
    String beanName = splitstrs[splitstrs.length-2];

    Object service = CrontabTask.getBean(beanName.substring(0, 1).toLowerCase()+beanName.substring(1, beanName.length()));
    vo = new ParamVo();
    vo.setParam(JSON.parseObject(form.get("params")+"",Map.class));

    Class serviceBean = Class.forName(paramValue.substring(0,paramValue.lastIndexOf(".")));
    Method m = serviceBean.getMethod(paramValue.substring(paramValue.lastIndexOf(".")+1,paramValue.length()),Class.forName("com.bonc.business.tools.ParamVo"));
    result = m.invoke(service,vo);
    try{
    Map<String,Object> resMap = (Map<String, Object>) result;
    code = (String) resMap.get("code");
    msg = (String) resMap.get("msg");
    obj = resMap.get("data");
    }catch(Exception ex){
    obj = result;
    }

    }
    }else{
    code = CST.RES_EXCEPTION;
    msg = "无此服务接口,请联系接口提供方解决!";
    }
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    code = CST.RES_EXCEPTION;
    msg = e.getMessage();
    if(e.getMessage().indexOf("syntax error")!=-1){
    msg = "传输的参数不是约定的有效的json格式字符串,请检查json字符串是否包含action和params!";
    }else{
    msg += "调用接口执行出错!";
    }
    }

    //插入接口调用日志信息
    /*try {
    interfacelogid = executorAsynTaskService.txAsynSaveInterfaceLog(request,createStaff,resmethod,resparams,code,obj,interfacelogid,msg);
    } catch (TxException e) {
    e.printStackTrace();
    }*/

    resultJsonStr = Ajax.responseString(code,msg,interfacelogid,obj);
    if(encyptbase64){
    resultJsonStr = Encypt.setEncString(resultJsonStr);
    }
    return resultJsonStr;
    }

    }

    3、postman检测接口是否可以正常调用

    http://127.0.0.1:8080/rdpe-shanxi/rest/commonApiRestful.action?jsonStr={
    "action": "txMktSmsSend",
    "params": {
    "pageNo" : 3,
    "busiCode" : "",
    "triggerCount" : "",
    "eventType" : ""
    }
    }

  • 相关阅读:
    Rabbitmq的使用四_Java Client方式使用Topic模式
    CentOS7安装Redis
    nmon文件结果分析
    nmon安装
    jmeter+ant+jenkins
    jenkins插件下载加速
    jmeter:多机联合负载
    jmeter Linux负载机出错Server failed to start:
    jenkins安装
    fiddler:筛选请求响应
  • 原文地址:https://www.cnblogs.com/ying1314/p/11727422.html
Copyright © 2011-2022 走看看