java 后台远程调用

346 阅读4分钟

前言

记录一些后台调用的方式

1.调用远程的wsdl文件

 public static String getDhServcie(String url, String info) {
    BaseLog.IBusinessInfo("地址:" + url);
    BaseLog.IBusinessInfo("参数:" + info);
    String result = null;
    //nameSpqce :命名空间
    String nameSpace="";
    try {
        // 直接引用远程的wsdl文件
        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setTargetEndpointAddress(new java.net.URL(url));
        call.setUseSOAPAction(true);
        call.setSOAPActionURI("nameSpace/"+"InvoiceImageMsgDel");
        call.setOperationName(new QName("nameSpace/", "InvoiceImageMsgDel"));// WSDL里面描述的方法名
        call.addParameter(new QName("nameSpace/", "info"),//参数名
                XMLType.SOAP_STRING, //参数类型
                ParameterMode.IN);// 参数模式 IN OR OUT
        call.setReturnType(org.apache.axis.encoding.XMLType.SOAP_STRING);// 设置返回类型
        result = (String) call.invoke(new Object[]{info});  //远程调用
    } catch (Exception e) {
        BaseLog.IBusinessError("调用失败!", e);
    }
    return result;
}

2.使用post方式转调服务

//入参为json对象
private static JSONObject post(String url, JSONObject json) throws Exception {
    JSONObject responseData = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = null;
    httpPost = new HttpPost(url);
    StringEntity postEntity = new StringEntity(json.toString(), Consts.UTF_8);
    postEntity.setContentType("application/json");
    httpPost.setEntity(postEntity);
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            responseData = JSONObject.parseObject(IOUtils.toString(entity.getContent(), "UTF-8"));
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if(response!=null){
            response.close();
        }
        httpClient.close();
    }

    return responseData;
}

//入参为json数组
public static JSONObject post(String url, JSONArray jsonArray) throws Exception {
    JSONObject responseData = null;
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = null;
    httpPost = new HttpPost(url);
    StringEntity postEntity = new StringEntity(jsonArray.toString(), Consts.UTF_8);
    postEntity.setContentType("application/json");
    httpPost.setEntity(postEntity);
    CloseableHttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            responseData = JSONObject.fromObject(IOUtils.toString(entity.getContent(), "UTF-8"));
        }
    } catch (Exception e) {
        throw e;
    } finally {
        response.close();
        httpClient.close();
    }

    return responseData;
}

3.直接拼接参数报文,解析xml格式数据

StringBuilder soapHeader = new StringBuilder();
        soapHeader.append("<soapenv:Envelope xmlns:soapenv=\"对应soapui头部地址\" xmlns:sch=\"对应soapui头部地\">");
        soapHeader.append("<soapenv:Header/>");
        soapHeader.append("<soapenv:Body>");
        soapHeader.append("<sch:param>");
        soapHeader.append("<sch:document_number>" + barcode + "</sch:document_number>");
        soapHeader.append("</sch:param>");
        soapHeader.append("</soapenv:Body>");
        soapHeader.append("</soapenv:Envelope>");
        log.info("输入参数报文:" + soapHeader.toString());

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL postUrl = new URL(url);
            connection = (HttpURLConnection) postUrl.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty(
                    "Content-Type",
                    "text/xml;charset=utf-8");
            connection.setRequestProperty("SOAPAction", "execute");
            connection.connect();
            DataOutputStream out =new DataOutputStream(connection.getOutputStream());
            out.write(soapHeader.toString().getBytes("UTF-8"));
            out.flush();
            out.close(); // flush and close
            reader =new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String line = "";
            while ((line = reader.readLine()) != null) {
                result = result + line;
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            reader.close();
            connection.disconnect();
        }
        
        //解析返回值
         try {
            Document document = DocumentHelper.parseText(result);
            //获取根节点
            Element rootElt = document.getRootElement();

            Iterator bodyIter = rootElt.elementIterator("Body"); //获取根节点下的子节点Body
            while(bodyIter.hasNext()){
                Element bodyEless = (Element)bodyIter.next();
                Iterator responseIter = bodyEless.elementIterator("soapResponse");
                while(responseIter.hasNext()){
                    Element responseEless = (Element)responseIter.next();
                    String status = responseEless.elementTextTrim("status");
                    message = responseEless.elementTextTrim("message");
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

4.用POST(GET) 调用接口

private static String  getinvoiceinfo(String barcode) {
    StringBuilder sb = new StringBuilder();
    try {
        String urlstr=AppConfig.publicConfig("4000000001")+"/app/getInvoices.do?barcode="+barcode;
        //String urlstr="http://ip:端口/SiitApp/app/getInvoices.do?barcode=JST-FSSC219202000140";
        log.info("调用接口地址:"+urlstr);
        URL url = new URL(urlstr);
        //打开和url之间的连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        PrintWriter out = null;
        /**设置URLConnection的参数和普通的请求属性****start***/
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conn.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
        /**设置URLConnection的参数和普通的请求属性****end***/
        //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
        //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
        //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
        conn.setDoOutput(true);
        conn.setDoInput(true);

        conn.setRequestMethod("GET");//GET和POST必须全大写
        conn.connect();
        //获取URLConnection对象对应的输入流
        InputStream is = conn.getInputStream();
        //构造一个字符流缓存
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
        String str = "";
        while ((str = br.readLine()) != null) {
            str=new String(str.getBytes());//解决中文乱码问题
            sb.append(str);
        }

        //关闭流
        is.close();
        //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
        //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
        conn.disconnect();
        System.out.println("完整结束");

    } catch (Exception e) {
        log.info(e.getMessage());
    }
    return sb.toString();
}

post方式调用传两个参数

private static String  getinvoiceinfo(String urlstr,String code) {
    StringBuilder sb = new StringBuilder();
    try {
        BaseLog.IBusinessInfo("调用接口地址:"+urlstr);
        URL url = new URL(urlstr);
        //打开和url之间的连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //PrintWriter out = null;
        /**设置URLConnection的参数和普通的请求属性****start***/
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conn.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
        /**设置URLConnection的参数和普通的请求属性****end***/
        //设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
        //最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
        //post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
        conn.setDoOutput(true);
        conn.setDoInput(true);			
        conn.setRequestMethod("POST");//GET和POST必须全大写

        // Post 请求不能使用缓存
        conn.setUseCaches(false);
        //设置本次连接是否自动重定向
        conn.setInstanceFollowRedirects(true);
        // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
        // 意思是正文是urlencoded编码过的form参数
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        conn.connect();

        DataOutputStream outs = new DataOutputStream(conn
                .getOutputStream());
        // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
        String content = "LoginType=GX&code=" + URLEncoder.encode(code, "UTF-8");
        // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写到流里面
        outs.writeBytes(content);
        //流用完记得关
        outs.flush();
        outs.close();

        //获取URLConnection对象对应的输入流
        InputStream is = conn.getInputStream();
        //构造一个字符流缓存
        BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
        String str = "";
        while ((str = br.readLine()) != null) {
            str=new String(str.getBytes());//解决中文乱码问题
            sb.append(str);
        }

        //关闭流
        is.close();
        //断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
        //固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
        conn.disconnect();
        BaseLog.IBusinessInfo("完整结束");

    } catch (Exception e) {
        BaseLog.IBusinessInfo(e.getMessage());
    }
    return sb.toString();
}

生成webservice本地客户端调用

1、将wsdl地址复制到SOAPUI中访问,通过Axis2生成本地客户端文件

image.png

image.png

image.png 2、将本地生成的客户端文件复制到项目中,修改文件目录

3、调用方式:

image.png 这里的url取SOAPUI上地址

image.png 如果需要设置请求用户名、密码,超时时间,可用这种方式:

image.png

暂时记录这些,后续再添加