java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java调用WebService接口

Java使用Soap方式调用WebService接口代码示例

作者:xjz_2002

Java调用WebService接口是指通过Java语言来访问并与WebService进行交互,WebService是一种基于Web的服务架构,它通过标准的XML和HTTP协议来提供服务,这篇文章主要给大家介绍了关于Java使用Soap方式调用WebService接口的相关资料,需要的朋友可以参考下

pom文件依赖

<dependencies>
   <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.13.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.83</version>
    </dependency>

    <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.8.15</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
    </dependency>
</dependencies>

测试类WebServiceTest.java

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.text.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.nio.charset.Charset;

public class WebServiceTest {

    public static void main(String[] args) throws JsonProcessingException {
        String url = "http://192.168.2.243:9018/sjz_mete_api.asmx?op=USMI_SanWeiSecondData";
        // 根据实际情况拼接xml
        String xmlData = "<soap:Envelope\n" +
                "    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                "    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n" +
                "    xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                "    <soap:Body>\n" +
                "    <USMI_SanWeiSecondData xmlns=\"http://10.48.98.122:82/\">\n" +
                "    <resultType>" + "json" + "</resultType>\n" +
                "    <arrStation>\n" +
                "       <string>" + "HJ001" + "</string>\n" +
                "    </arrStation>\n" +
                "    <beginDate>" + "2023-12-02 12:00:00" + "</beginDate>\n" +
                "    <endDate>" + "2022-12-02 12:00:59" + "</endDate>\n" +
                "    </USMI_SanWeiSecondData>\n" +
                "    </soap:Body>\n" +
                "</soap:Envelope>";

        String postSoap = doPostSoap(url, xmlData, "http://10.48.98.122:82/USMI_SanWeiSecondData");

        JSONObject jsonObject = SoapResponseParser(postSoap);
        System.out.println("unPostSoap===========" + postSoap);
        System.out.println("jsonObject===========" + jsonObject);

    }

    //soap响应的数据解析,放到json对象中并返回
    public static JSONObject SoapResponseParser(String soapResponse) throws JsonProcessingException {
        // 去除XML转义字符
        String jsonContent = StringEscapeUtils.unescapeXml(soapResponse);

        // 找到JSON数组的开始位置和结束位置
        int startIndex = jsonContent.indexOf("[");
        int endIndex = jsonContent.indexOf("]");
        JSONObject jsonObject = new JSONObject();

        if ((startIndex) != -1 && (endIndex) != -1) {
            // 提取JSON数组部分
            String jsonString = jsonContent.substring(startIndex, endIndex + 1);

            // 初始化ObjectMapper
            ObjectMapper objectMapper = new ObjectMapper();
            // 将JSON字符串解析为JsonNode(树状结构表示)
            JsonNode jsonNode = objectMapper.readTree(jsonString);
            // 如果是JSON数组,可以直接获取数组元素
            if (jsonNode.isArray()) {
                for (JsonNode element : jsonNode) {
                    jsonObject.put("站号", element.get("站号").asText());
                    jsonObject.put("站名", element.get("站名").asText());
                    jsonObject.put("日期", element.get("日期").asText());
                    jsonObject.put("总风速", element.get("总风速").asText());
                    jsonObject.put("水平风速", element.get("水平风速").asText());
                    jsonObject.put("垂直风向", element.get("垂直风向").asText());
                    jsonObject.put("水平风向", element.get("水平风向").asText());
                    jsonObject.put("风速U", element.get("风速U").asText());
                    jsonObject.put("风速V", element.get("风速V").asText());
                    jsonObject.put("风速W", element.get("风速W").asText());
                }
            }

        }
        return jsonObject;

    }

    //使用SOAP1.1发送消息
    public static String doPostSoap(String postUrl, String soapXml, String soapAction) {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(postUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(6000)
                .setConnectTimeout(6000).build();
        httpPost.setConfig(requestConfig);
        try {
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", soapAction);
            StringEntity data = new StringEntity(soapXml, Charset.forName("UTF-8"));
            httpPost.setEntity(data);
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                // 打印响应内容
                retStr = EntityUtils.toString(httpEntity, "UTF-8");
                System.out.println("response:" + retStr);
            }
            // 释放资源
            closeableHttpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retStr;
    }
}

总结 

到此这篇关于Java使用Soap方式调用WebService接口的文章就介绍到这了,更多相关Java调用WebService接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文