码迷,mamicode.com
首页 > Web开发 > 详细

09_httpclietn测试SOAP协议

时间:2016-09-04 20:43:29      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

【工程截图】注意:无需使用Wsimport生成客户端代码

技术分享

 

【HttpClient.java】

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpClient {
    
    public static void main(String[] args) throws IOException {
        
        //开启 一个http链接
        //webservice地址
        URL url = new URL("http://127.0.0.1:12345/weather");
        
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        
        //设置post请求,post是大写
        httpURLConnection.setRequestMethod("POST");
        //Content-Type: text/xml; charset=utf-8
        httpURLConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
        
        //设置请求和响应
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        
        String requestString = requestString("郑州");
        //发送soap协议
        httpURLConnection.getOutputStream().write(requestString.getBytes());
        
        //接收响应内容
        
        InputStream inputStream = httpURLConnection.getInputStream();
        
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        
        int len=-1;
        byte[] b = new byte[1024];
        //将inputStream内容写到byteArrayOutputStream
        while((len= inputStream.read(b, 0, 1024))!=-1){
            byteArrayOutputStream.write(b, 0, len);
        }
        
        //获取响应内容 
        String responseString = byteArrayOutputStream.toString();
        
        System.out.println(responseString);
        
        //解析响应的xml数据。
        //....
        inputStream.close();
        byteArrayOutputStream.close();
    }
    
    /**
    <?xml version="1.0" ?>
        <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
            <S:Body>
                <ns2:queryWeather xmlns:ns2="http://server.weather.jaxws.Higgin.com/">
                    <arg0>郑州</arg0>
                </ns2:queryWeather>
            </S:Body>
    </S:Envelope>
     */
    //soap协议内容,请求的 内容
    private static String requestString(String cityName){
        String xmlString = "<?xml version=\"1.0\" ?>" +
                "<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<S:Body>" +
                "<ns2:queryWeather xmlns:ns2=\"http://server.weather.jaxws.Higgin.com/\">" +
                "<arg0>"+cityName+"</arg0>" +
                        "</ns2:queryWeather>" +
                        "</S:Body>" +
                        "</S:Envelope>";
        return xmlString;
    }
}

 【运行结果】

(注意:要先开启WebService服务)

技术分享

(需要进一步解析出自己所需的数据,使用正则表达式)

09_httpclietn测试SOAP协议

标签:

原文地址:http://www.cnblogs.com/HigginCui/p/5840044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!