HttpURLConnection 发送Soap get/post请求

Soap: Simple Object Access Protocol ——简单对象访问协议
        1.soap作为一个基于xml语言的协议用于网上传输数据
        2.SOAP = HTTP + XML
        3.SOAP是基于HTTP的 (这里顺便补充一下,Http是基于Socket的)
        4.SOAP的组成如下
               1.Envelope: 必须的,以XML根元素出现
               2.Header:可选的
               3.Body:必须的,在body部分包含一些,执行服务器的方法,和发送到服务器的数据    

 


/**
 * soap较rest具有比较好的可靠性与安全性
 * 
 * soap是一种固定的规范
 * 
 * 能够满足应用上下文信息与对话状态管理
 * 
 * @author xxx
 *
 */
public class HttpUrlConnectionSoap {

    private static final Logger LOG = LoggerFactory.getLogger(HttpUrlConnectionSoap.class);

    public static String Get(List<String> params) {

        String url = "http://localhost:8080/Base/testGet?username=" + params.get(0);
        int timeout = 5000;

        try {
            // httpUrlConnection发送Soap请求
            URL url2 = new URL(url);

            // 创建httpUrlConnection对象
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();

            // 设置超时时间
            connection.setConnectTimeout(timeout);
            connection.setReadTimeout(timeout);
            connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 是否使用缓存
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            // 执行请求返回响应码
            int responseCode = connection.getResponseCode();
            String responseMsg = "";
            // 通过响应码,判断连接是否成功
            if (responseCode >= HttpsURLConnection.HTTP_OK && responseCode <= HttpsURLConnection.HTTP_BAD_REQUEST) {
                // 连接成功,获取响应内容
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line = "";
                if ((line = reader.readLine()) != null) {
                    responseMsg += line + "\n";
                }
            }
            return responseMsg;
        } catch (IOException e) {
            LOG.error("IOException", e);
        }
        return null;
    }

    public static String Post(List<String> params) {

        String url = "http://localhost:8080/Base/testPost";
        int timeout = 5000;

        // 线程安全
        StringBuffer buffer = new StringBuffer("");

        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<soap:Envelope " + "xmlns:api='http://demo.ls.com/' "
                + "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
                + "xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
                + "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
        buffer.append("<soap:Body>");
        buffer.append("<api:sayHello>");
        buffer.append("<arg0>ls</arg0>");
        buffer.append("</api:sayHello>");
        buffer.append("</soap:Body>");
        buffer.append("</soap:Envelope>");

        try {
            // httpUrlConnection发送Soap请求
            URL url2 = new URL(url);

            // 创建httpUrlConnection对象
            HttpURLConnection connection = (HttpURLConnection) url2.openConnection();

            // 设置超时时间
            connection.setConnectTimeout(timeout);
            connection.setReadTimeout(timeout);
            connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
            // 设置请求方式
            connection.setRequestMethod("POST");
            // 是否使用缓存
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            OutputStream outputStream = connection.getOutputStream();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
            writer.write(buffer.toString());
            writer.flush();

            // 执行请求返回响应码
            int responseCode = connection.getResponseCode();
            String responseMsg = "";
            // 通过响应码,判断连接是否成功
            if (responseCode >= HttpsURLConnection.HTTP_OK && responseCode <= HttpsURLConnection.HTTP_BAD_REQUEST) {
                // 连接成功,获取响应内容
                InputStream is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line = "";
                if ((line = reader.readLine()) != null) {
                    responseMsg += line + "\n";
                }
            }
            return responseMsg;
        } catch (IOException e) {
            LOG.error("IOException", e);
        }

        return null;
    }

}
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpURLConnection 是 Java 中用于发送 HTTP 请求的类,其中包括发送 SOAP 请求。在使用 HttpURLConnection 发送 SOAP 请求时,需要将 SOAP 消息作为 HTTP 请求发送给服务器。以下是一个简单的示例: ```java URL url = new URL("http://example.com/soap"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8"); String soapMessage = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\"http://example.com/soap/service\">\n" + " <soapenv:Header/>\n" + " <soapenv:Body>\n" + " <ser:MySoapService>\n" + " <ser:inputParam>hello world</ser:inputParam>\n" + " </ser:MySoapService>\n" + " </soapenv:Body>\n" + "</soapenv:Envelope>"; OutputStream os = conn.getOutputStream(); os.write(soapMessage.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } InputStream is = conn.getInputStream(); // 使用 SAX 解析 SOAP 响应 SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = saxParserFactory.newSAXParser(); MySoapResponseHandler handler = new MySoapResponseHandler(); saxParser.parse(is, handler); String output = handler.getOutput(); System.out.println(output); conn.disconnect(); ``` 在上面的示例中,我们首先创建一个 HttpURLConnection 对象,并设置请求方法为 POST请求头中包括 Content-Type 为 text/xml;charset=UTF-8。然后,我们将 SOAP 消息作为请求体写入输出流中,并发送请求。如果响应码为 HTTP_OK,则表示请求成功,我们可以获取输入流,使用 SAXParser 对 SOAP 响应进行解析。解析过程中,我们需要自定义一个 SAX 解析处理器 MySoapResponseHandler,用于处理 SOAP 响应中的内容。最后,我们可以从处理器中获取解析结果,输出到控制台。最后别忘了关闭连接。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值