Java代码实现SOAP和REST接口工具类

SOAP(Simple Object Access Protocol)和REST(Representational State Transfer)是两种不同的Web服务通信协议,因此它们的接口工具类实现也有一些差异。

以下是一个简单的Java代码实现SOAP接口工具类的示例:

import javax.xml.namespace.QName;
import javax.xml.soap.*;

public class SoapClientUtil {

    private final String endpoint;
    private final String namespace;
    private boolean validate = false;

    public SoapClientUtil(String endpoint, String namespace) {
        this.endpoint = endpoint;
        this.namespace = namespace;
    }

    public void setValidate(boolean validate) {
        this.validate = validate;
    }

    public SOAPMessage sendMessage(String methodName, Object... params) throws Exception {
        
        // Create a SOAP message
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMessage = factory.createMessage();

        // Add SOAP envelope, header, and body elements
        SOAPEnvelope envelope = soapMessage.getSOAPPart().getEnvelope();
        if (validate) {
            envelope.addNamespaceDeclaration("xsd", "http://www.w3.org/2001/XMLSchema");
            envelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance");
            envelope.addNamespaceDeclaration("SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
            envelope.setAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "noNamespaceSchemaLocation", "uss.xsd");
        }
        SOAPHeader header = envelope.getHeader();
        SOAPBody body = envelope.getBody();

        // Create the SOAP body message
        QName bodyName = new QName(namespace, methodName);
        SOAPBodyElement bodyElement = body.addBodyElement(bodyName);

        if (params != null) {
            for (Object param : params) {
                QName paramName = new QName(param.getClass().getName());
                SOAPElement soapElement = bodyElement.addChildElement(paramName);
                soapElement.setTextContent(param.toString());
            }
        }

        // Send the SOAP message to the endpoint and receive a response
        SOAPConnectionFactory connectionFactory = SOAPConnectionFactory.newInstance();
        SOAPConnection connection = connectionFactory.createConnection();
        SOAPMessage response = connection.call(soapMessage, endpoint);
        connection.close();

        return response;
    }
}

以下是一个简单的Java代码实现REST接口工具类的示例:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class RestClientUtil {

    private final String endpoint;

    public RestClientUtil(String endpoint) {
        this.endpoint = endpoint;
    }

    public String sendRequest(String method, String... params) throws Exception {
        
        // Build the request URL
        StringBuilder urlBuilder = new StringBuilder(endpoint);
        if (params != null && params.length > 0) {
            urlBuilder.append("?");
            for (int i = 0; i < params.length; i += 2) {
                urlBuilder.append(params[i]);
                urlBuilder.append("=");
                urlBuilder.append(params[i+1]);
                if (i < params.length - 2) {
                    urlBuilder.append("&");
                }
            }
        }
        URL url = new URL(urlBuilder.toString());

        // Open a connection using the specified HTTP method
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);

        // Read the response from the server
        StringBuilder response = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
        }
        rd.close();

        // Close the HTTP connection
        conn.disconnect();

        return response.toString();
    }
}

需要注意的是,这些示例代码只实现了最基本的功能,实际使用时可能需要根据具体情况进行修改和扩展。同时还需要注意安全性和性能等方面的问题,例如SSL证书验证、连接池管理和结果缓存等。

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Apache CXF是一个流行的Java Web Services框架,它支持RESTSOAP协议,并且提供了丰富的功能和工具,可以帮助开发者快速开发Web Services应用程序。 以下是使用Apache CXF编写一个RESTSOAPSOAPREST的转换程序的示例: 1. 添加依赖 首先需要在项目中添加Apache CXF的依赖,可以在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-core</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxrs</artifactId> <version>3.4.0</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.4.0</version> </dependency> ``` 2. 编写接口 定义一个接口,包含需要暴露的方法,例如: ```java @Path("/user") public interface UserService { @GET @Path("/{id}") @Produces("application/json") User getUserById(@PathParam("id") String id); @POST @Path("/") @Consumes("application/json") void addUser(User user); } ``` 3. 实现接口 实现接口,并使用CXF提供的注解将其暴露为RESTSOAP服务,例如: ```java public class UserServiceImpl implements UserService { @Override public User getUserById(String id) { // 从数据库或其他数据源获取用户信息 User user = new User(); user.setId(id); user.setName("Alice"); user.setAge(20); return user; } @Override public void addUser(User user) { // 将用户信息保存到数据库或其他数据源 System.out.println("Add user: " + user); } } ``` 4. 配置CXF 使用CXF提供的配置方式,将实现类暴露为RESTSOAP服务,例如: ```xml <jaxrs:server id="restUserService" address="/"> <jaxrs:serviceBeans> <ref bean="userService"/> </jaxrs:serviceBeans> </jaxrs:server> <jaxws:endpoint id="soapUserService" address="/UserService"> <jaxws:serviceBean> <ref bean="userService"/> </jaxws:serviceBean> </jaxws:endpoint> ``` 5. 测试 启动应用程序,并使用浏览器或SOAP客户端发送请求,测试RESTSOAP服务的功能。例如: REST服务:http://localhost:8080/user/1 SOAP服务: ```xml <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:user="http://example.com/user"> <soapenv:Header/> <soapenv:Body> <user:getUserById> <user:id>1</user:id> </user:getUserById> </soapenv:Body> </soapenv:Envelope> ``` 以上就是使用Apache CXF编写RESTSOAPSOAPREST的转换程序的示例。需要注意的是,该示例仅用于演示,实际应用中还需要进行更多的配置和调整,以满足实际需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值