java调用webservice服务

java调用webservice服务代码笔记:

package com.ws.client;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/10/24.
 */
public class WSClient {
    public static  void  main(String[] args)throws  Exception{
        String address = "http://localhost:8080/Spring_WebService/HelloWorld?wsdl";
//        client_1(address);
        client_2("Leitao",address);
        String soap = addNumSoapXMl(13, 4);
//        String returnStr = httpClientWebServiceClient_1(soap,address);
//        String returnStr = httpClientWebServiceClient_2(soap, address);


//        System.out.println(returnStr);

        System.exit(0);
    }
    public  static  void  client_1(String address){
        //动态调用
        JaxWsDynamicClientFactory dynamicClientFactory = JaxWsDynamicClientFactory.newInstance();
        Client client = dynamicClientFactory.createClient(address);
        System.out.println("===" + client);
        try {
            Object [] results = client.invoke("sayHello", "LeiTao");
            System.out.println(results[0]);
            Object [] results1 = client.invoke("addNum", 10, 20);
            System.out.println(results1[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public  static  void  client_2(String userName,String webServiceUrl) throws  Exception{
        String soap = sayHelloSoapXMl(userName);
        //服务的地址
        URL wsUrl = new URL(webServiceUrl);
        //建立连接
        HttpURLConnection connection = (HttpURLConnection) wsUrl.openConnection();
        //设置参数
        connection.setDoInput(true);
        connection.setDoOutput(true);
        //设置超时时间
        connection.setConnectTimeout(4000);
        connection.setReadTimeout(4000);
        //设置请求方式
        connection.setRequestMethod("POST");
        //报文头配置
        connection.setRequestProperty("Content-Type", "Content-Type: text/xml;charset=UTF-8");
        // 生成输出流
        OutputStream outputStream = connection.getOutputStream();
        //推送字节流
        outputStream.write(soap.getBytes());
        // 接收返回流
        InputStream inputStream = connection.getInputStream();
        // 流转成字符串
        int len=0;
        String string="";
        byte[] b = new byte[1024];
        while ((len = inputStream.read(b)) != -1) {
            String strings = new String(b, 0, len, "UTF-8");
            string += strings;
        }
        String json = string.replaceAll("(?is).*?<return>(.*?)</return>.*", "$1");//取出返回值
        System.out.println(json);
    }
    /*********************httpclient 访问Webservice*************************/
    private static  String  httpClientWebServiceClient_1(String soap, String webServiceUrl){
        String string = null;
        try {
            PostMethod postMethod = new PostMethod(webServiceUrl);
            // 然后把Soap请求数据添加到PostMethod中
            byte[] b = soap.getBytes("utf-8");
            InputStream is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml;charset=UTF-8");
            postMethod.setRequestEntity(re);
            // 最后生成一个HttpClient对象,并发出postMethod请求
            HttpClient httpClient = new HttpClient();
            // 链接超时
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
            //读取超时
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(10000);
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == 200) {
                string = postMethod.getResponseBodyAsString().trim().replaceAll("<", "<").replaceAll(">", ">").replaceAll(""", "\"");
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return string;
    }
    private static  String httpClientWebServiceClient_2(String soap, String webServiceUrl) {
        String string = null;
        try {
            PostMethod postMethod = new PostMethod(webServiceUrl);
            // 然后把Soap请求数据添加到PostMethod中
            byte[] b = soap.getBytes("utf-8");
            InputStream is = new ByteArrayInputStream(b, 0, b.length);
            RequestEntity re = new InputStreamRequestEntity(is, b.length, "application/soap+xml; charset=utf-8");
            postMethod.setRequestEntity(re);
            // 最后生成一个HttpClient对象,并发出postMethod请求
            HttpClient httpClient = new HttpClient();
            // 链接超时
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
            //读取超时
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(10000);
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode == 200) {
                string = postMethod.getResponseBodyAsString().trim().replaceAll("<", "<").replaceAll(">", ">").replaceAll(""", "\"");
            }
        } catch (IllegalArgumentException e) {
           e.printStackTrace();
        } catch (IOException e) {
           e.printStackTrace();
        }
        return string;
    }



    /**
     * 封装soap  xml
     * @param userName
     * xmlns:ser="http://service.com.cn/  接口命名空间
     * @return
     */
    private static  String sayHelloSoapXMl(String userName) {
        StringBuffer soap = new StringBuffer();
        soap.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.com.cn/\">");
        soap.append(" <soapenv:Header/>");
        soap.append(" <soapenv:Body>");
        soap.append(" <ser:sayHello>");
        soap.append(" <arg0>");
        soap.append(userName);
        soap.append("</arg0>");
        soap.append(" </ser:sayHello>");
        soap.append("</soapenv:Body>");
        soap.append("</soapenv:Envelope>");
        return soap.toString();
    }
    private static  String addNumSoapXMl(int a,int b) {
        StringBuffer soap = new StringBuffer();
        soap.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://service.com.cn/\">");
        soap.append(" <soapenv:Header/>");
        soap.append(" <soapenv:Body>");
        soap.append(" <ser:addNum>");
        soap.append(" <a>");
        soap.append(a);
        soap.append("</a>");
        soap.append(" <b>");
        soap.append(b);
        soap.append("</b>");
        soap.append(" </ser:addNum>");
        soap.append("</soapenv:Body>");
        soap.append("</soapenv:Envelope>");
        return soap.toString();
    }


}


源码地址:

client:http://download.csdn.net/detail/admin1973/9852192

server:http://download.csdn.net/detail/admin1973/9852205


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值