zoukankan      html  css  js  c++  java
  • call web service with httpclient

    import com.sun.xml.internal.messaging.saaj.soap.Envelope;
    import org.apache.commons.io.IOUtils;
    import org.apache.commons.lang3.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 org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.charset.Charset;
    import java.nio.charset.StandardCharsets;
    import java.util.List;
    
    public class WebServiceTest2 {
        public static void main(String[] args) throws IOException {
            String url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl";
            // 根据实际情况拼接xml
            StringBuilder xmlData = new StringBuilder("");
            xmlData.append("<?xml version="1.0" encoding="UTF-8"?>");
            xmlData.append("<soapenv:Envelope "
                    + "    xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' "
                    + " xmlns:q0='http://WebXml.com.cn/' "
                    + "    xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
                    + " xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' >");
            xmlData.append("<soapenv:Body>");
            xmlData.append("<q0:getWeatherbyCityName>");
            xmlData.append("<q0:theCityName>上海</q0:theCityName> ");
            xmlData.append("</q0:getWeatherbyCityName>");
            xmlData.append("</soapenv:Body>");
            xmlData.append("</soapenv:Envelope>");
    
            String postSoap = doPostSoap(url, xmlData.toString(), "");
            // 去除转义字符
            /*String unPostSoap = StringEscapeUtils.unescapeXml(postSoap);
            System.out.println(unPostSoap);*/
        }
    
        //使用SOAP1.1发送消息
        public static String doPostSoap(String postUrl, String soapXml, String soapAction) throws IOException {
            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=utf8");
                //httpPost.setHeader("SOAPAction", soapAction);
                StringEntity requestEntity = new StringEntity(soapXml, StandardCharsets.UTF_8);
                httpPost.setEntity(requestEntity);
    
                CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
                HttpEntity entity = response.getEntity();
    
    //            InputStream content = entity.getContent();
    //            String result = IOUtils.toString(content);
                //Document dc = strXmlToDocument(result);
    
                if (entity != null) {
                    // 打印响应内容
                    retStr = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("response:" + retStr);
                }
                // 释放资源
                closeableHttpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return retStr;
        }
        public static Document strXmlToDocument(String parseStrXml){
            Document document = null;
            try {
                document = DocumentHelper.parseText(parseStrXml);
                Element root = document.getRootElement();
                List<Element> list = root.elements();
                getElement(list);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            return document;
        }
    
        // 递归读取子元素
        private static void getElement(List<Element> sonElemetList) {
    //        Map<String,String> map = new HashMap<String, String>();
            for (Element sonElement : sonElemetList) {
                if (sonElement.elements().size() != 0) {
                    System.out.println(sonElement.getName() + ":");
                    getElement(sonElement.elements());
                }else{
                    System.out.println(sonElement.getName() + ":"+ sonElement.getText());
                }
    
            }
        }
    
    }
    
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    public class Test2 {
        public static void main(String[] args) throws IOException {
            //第一步:建立服務地址
            URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx?wsdl");
            //第二步:開啟一個通向服務地址的連線
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //第三步:設定引數
            //3.1傳送方式設定:POST必須大寫
            connection.setRequestMethod("POST");
            //3.2設定資料格式:content-type
            connection.setRequestProperty("content-type", "text/xml;charset=utf-8");
            //3.3設定輸入輸出,因為預設新建立的connection沒有讀寫許可權,
            connection.setDoInput(true);
            connection.setDoOutput(true);
    
            //第四步:組織SOAP資料,傳送請求
            String soapXML = getXML("12345");
            //將資訊以流的方式傳送出去
            OutputStream os = connection.getOutputStream();
            os.write(soapXML.getBytes());
            //第五步:接收服務端響應,列印
            int responseCode = connection.getResponseCode();
            if(200 == responseCode){//表示服務端響應成功
                //獲取當前連線請求返回的資料流
                InputStream is = connection.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
    
                StringBuilder sb = new StringBuilder();
                String temp = null;
                while(null != (temp = br.readLine())){
                    sb.append(temp);
                }
    
                /**
                 * 列印結果
                 */
                System.out.println(sb.toString());
    
                is.close();
                isr.close();
                br.close();
            }
            os.close();
        }
    
    
        public static String getXML(String phone){
    
            String soapXML = "<?xml version="1.0" encoding="utf-8"?>"
                    +"<soap:Envelope xmlns:xsi="http://www.w3.org/2003/XMLSchema-instance" "
                    +"xmlns:web="http://WebXml.com.cn/"  "
                    +"xmlns:xsd="http://www.w3.org/2003/XMLSchema" "
                    +"xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">"
                    +"<soap:Body>"
                    +"<web:getMobileCodeInfo>"
                    +phone
                    +"</web:getMobileCodeInfo>"
                    +"</soap:Body>"
                    +"</soap:Envelope>";
            return soapXML;
        }
    }
    
  • 相关阅读:
    【Lucene3.6.2入门系列】第14节_SolrJ操作索引和搜索文档以及整合中文分词
    最短路--Dijkstra算法 --HDU1790
    XMPPFrameWork IOS 开发(六)聊天室
    InfoSphere BigInsights 安装部署
    EXCEL VBA运行不显示系统提示
    android 随手记 倒计时
    Conversion between json and object
    java 运行项目不放到tomcat下的webapps文件夹下放到自己建的文件夹中的处理办法
    sBPM产品介绍
    linux进程,作业,守护进程,进程间同步
  • 原文地址:https://www.cnblogs.com/land-fill/p/14846301.html
Copyright © 2011-2022 走看看