Loading

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;
    }
}
posted @ 2021-06-03 17:51  landfill  阅读(44)  评论(0编辑  收藏  举报