webService

本文详细介绍了如何进行WebService的实践操作,包括服务端的远程服务设置,客户端的远程服务调用,以及利用HttpClient进行数据交互的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.服务端远程服务
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.constants.Style;
import org.apache.axis.constants.Use;
import org.apache.axis.description.OperationDesc;
import org.apache.axis.description.ParameterDesc;

import javax.xml.namespace.QName;
import java.net.URL;
import java.util.Vector;

/**
 * @author yangyongzhen
 * @date 2019/11/8 21:23
 */
public class Demo {

    public static void main(String[] args) throws Exception {

        getWebServiceInfo("http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx");
    }

    public static String getWebServiceInfo(String url) throws Exception {

        OperationDesc oper = new OperationDesc();
        oper.setName("getStationName");
        ParameterDesc param;
        //创建service 实例
        Service service = new Service();
        //通过service 创建Call 实例
        Call call = (Call) service.createCall();
        //将Web Service的服务路径加入到call实例之中
        call.setTargetEndpointAddress(new URL(url));
        QName qname = new QName("http://WebXml.com.cn/", "getStationName");
        //设置调用远程方法的路径
        call.setOperationName(qname);
//        param = new ParameterDesc(new QName("http://WebXml.com.cn/","TrainCode"),ParameterDesc.IN,new QName("http://www.w3.org/2001/XMLSchema","String"),String.class,false,false);
//        param.setOmittable(true);
//        oper.addParameter(param);
//        param = new ParameterDesc(new QName("http://WebXml.com.cn/","UserId"),ParameterDesc.IN,new QName("http://www.w3.org/2001/XMLSchema","String"),String.class,false,false);
//        param.setOmittable(true);
//        oper.addParameter(param);
        //设置返回类型
        oper.setReturnType(new QName("http://xml.apache.org/xml-soap", "Vector"));
        oper.setStyle(Style.WRAPPED);
        oper.setUse(Use.LITERAL);
        call.setOperation(oper);
        call.setSOAPActionURI("http://WebXml.com.cn/getStationName");
        call.setUseSOAPAction(true);
//        call.setProperty(Call.SEND_TYPE_ATTR, Boolean.FALSE);
//        call.setProperty(AxisEngine.PROP_DOMULTIREFS, Boolean.FALSE);
//        call.setSOAPVersion(SOAPConstants.SOAP12_CONSTANTS);
        //调用方法,返回一维数组
        Vector<String> Msg = (Vector<String>) call.invoke(new Object[]{});
        System.out.println(Msg);
        return null;
    }
}


2.客户端远程服务
/**
 * @author yangyongzhen
 * @date 2019/11/4 17:53
 */


import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;

public class HttpClientHandler {

    private static final String URL = "http://127.0.0.1:port/api";

    public static String sendPost(String param) throws Exception {
        try {
            // 创建httpClient实例对象
            HttpClient httpClient = new HttpClient();
            // 设置httpClient连接主机服务器超时时间:15000毫秒
            httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(150000);
            // 设置post请求超时时间
            httpClient.getHttpConnectionManager().getParams().setSoTimeout(150000);
            // 创建post请求方法实例对象
            PostMethod postMethod = new PostMethod(URL);
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            postMethod.setRequestEntity(new StringRequestEntity(param, "text/xml", "UTF-8"));
            httpClient.executeMethod(postMethod);
            String result = null;
            if (postMethod.getStatusCode() == HttpStatus.SC_OK) {
                result = postMethod.getResponseBodyAsString();
                System.out.println("responseResult:" + result);
            } else {
                System.out.println("method.getStatusCode()" + postMethod.getStatusCode());
            }
            postMethod.releaseConnection();
            return result;
        } catch (HttpException e) {
            e.printStackTrace();
            throw new HttpException(e.getMessage());
        }
    }
}    
3.HttpClient
// Post请求,参数json字符串格式
public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }

    // Post请求,参数map格式
    public static String doHttpPost(String url, Map map) throws Exception {
        // 第一步:创建一个httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 第二步:创建一个HttpPost对象。需要指定一个url
            HttpPost post = new HttpPost(url);
            // 第三步:创建一个list模拟表单,list中每个元素是一个NameValuePair对象
            List<NameValuePair> formList = new ArrayList<>();
            // 可以根据传入的map遍历,比较懒就不写了
            formList.add(new BasicNameValuePair("name", "张三"));
            formList.add(new BasicNameValuePair("pass", "1243"));
            // 第四步:需要把表单包装到Entity对象中。StringEntity
            StringEntity entity = new UrlEncodedFormEntity(formList, "utf-8");
            post.setEntity(entity);
            // 第五步:执行请求。
            response = httpClient.execute(post);
            // 第六步:接收返回结果
            HttpEntity httpEntity = response.getEntity();
            result = EntityUtils.toString(httpEntity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    // Get请求,支持无参、单k-v、map集合参数格式
    public static String doHttpGet(String url, Map map) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 定义请求的参数
            URIBuilder uriBuilder = new URIBuilder(url);
            // 可以根据参数格式,单k-v或者集合调用不同的方法
            uriBuilder.setParameter("key", "value");
            URI remoteUrl = uriBuilder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(remoteUrl);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值