webservice介面呼叫

吃螺絲粉發表於2020-10-21

最近接了個簡訊介面用的是webservice,查了下資料接上的 。記錄一下

1.在url後面加上?wsdl獲取到 targetNamespace

2.下載soapui對介面進行測試。並獲取報文格式

3.最後就是根據報文組織查詢  直接上工具類吧 

package channel_ZhongXinJianTou;

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

import channel_ZhongZhouQH.Channel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


/**
 * Http方式呼叫WebService
 *
 */
public class Http {

    public  static Log log = LogFactory.getLog(Channel.class);

    private static String urlWsdl = "http://ip:port/com/SmsInterface.cfc?wsdl";
    private static String targetNamespace = "xxxxxx";//第一步獲取到的資料
    private static String OK = "<SendSmsReturn xsi:type=\"xsd:string\">0</SendSmsReturn>";

    /**
     * HttpURLConnection方式
     * @param soap
     */
    public static void httpURLConnection(String soap,String urlWsdl) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlWsdl);
            connection = (HttpURLConnection)url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            connection.setRequestProperty("SOAPAction", targetNamespace + "toTraditionalChinese");//+ "toTraditionalChinese"
            connection.connect();

            setBytesToOutputStream(connection.getOutputStream(), soap.getBytes());
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                byte[] b = getBytesFromInputStream(connection.getInputStream());
                String back = new String(b);
                System.out.println("httpURLConnection返回soap:" + back);
                //System.out.println("httpURLConnection結果:" + parseResult(back));
            } else {
                System.out.println("httpURLConnection返回狀態碼:" + connection.getResponseCode());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
    }

    /**
     * Commons-HttpClinet方式
     * @param soap
     */
    public static void commonsHttpClient(String soap) {
        try {
            org.apache.commons.httpclient.HttpClient httpclient = new org.apache.commons.httpclient.HttpClient();
            org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod(urlWsdl);
            post.addRequestHeader("Content-Type", "text/xml;charset=UTF-8");
            post.addRequestHeader("SOAPAction", targetNamespace + "toTraditionalChinese");
            org.apache.commons.httpclient.methods.RequestEntity entity = new org.apache.commons.httpclient.methods.InputStreamRequestEntity(new ByteArrayInputStream(soap.getBytes()));
            post.setRequestEntity(entity);
            int status = httpclient.executeMethod(post);
            if (status == org.apache.commons.httpclient.HttpStatus.SC_OK) {
                String back = post.getResponseBodyAsString();
                System.out.println("Commons-HttpClinet返回soap:" + back);
                //System.out.println("commons-HttpClinet返回結果:" + parseResult(back));
            } else {
                System.out.println("commons-HttpClinet返回狀態碼:" + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * HttpClient方式
     * @param soap
     */
    public static String httpClient(String soap,String urlWsdl) {
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(urlWsdl);
            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
            httpPost.setHeader("SOAPAction", targetNamespace );//+ "toTraditionalChinese"
            InputStreamEntity entity = new InputStreamEntity(new ByteArrayInputStream(soap.getBytes()));
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String back = EntityUtils.toString(responseEntity);
                log.info("httpClient返回soap:" + back);
                if (back.contains(OK)){
                    return "1,0";
                }else {
                    return "0,0";
                }
                //System.out.println("httpClient返回soap:" + back);
                //System.out.println("httpClient返回結果:" + parseResult(back));
            } else {
                log.info("HttpClinet返回狀態碼:" + response.getStatusLine().getStatusCode());
                //System.out.println("HttpClinet返回狀態碼:" + response.getStatusLine().getStatusCode());
                return "0,0";
            }
        } catch (Exception e) {
            log.info("異常"+e);
            e.printStackTrace();
            return "0,-100";
        }
    }



    /**
     * 從輸入流獲取資料
     * @param in
     * @return
     * @throws IOException
     */
    private static byte[] getBytesFromInputStream(InputStream in) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            baos.write(b, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        return bytes;
    }

    /**
     * 向輸入流傳送資料
     * @param out
     * @param bytes
     * @throws IOException
     */
    private static void setBytesToOutputStream(OutputStream out, byte[] bytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        byte[] b = new byte[1024];
        int len;
        while ((len = bais.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
    }


    /*private static String parseResult(String s) {
        String result = "";
        try {
            Reader file = new StringReader(s);
            SAXReader reader = new SAXReader();

            Map<String, String> map = new HashMap<String, String>();
            map.put("ns", "http://rpc.xml.coldfusion");
            reader.getDocumentFactory().setXPathNamespaceURIs(map);
            Document dc = reader.read(file);
            result = dc.selectSingleNode("//ns:toTraditionalChineseResult").getText().trim();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }*/

    public static void main(String[] args) {
        
        StringBuffer xMLcontent = new StringBuffer("");
        xMLcontent.append("<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:com=\"http://com\">");
        xMLcontent.append("   <soapenv:Header/>");
        xMLcontent.append("   <soapenv:Body>");
        xMLcontent.append("     <com:SendSms soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
        xMLcontent.append("<account xsi:type=\"xsd:string\">dx****</account>");
        xMLcontent.append("<password xsi:type=\"xsd:string\">dx****</password>");
        xMLcontent.append("<mobile xsi:type=\"xsd:string\">182****772</mobile>");
        xMLcontent.append("<servicecode xsi:type=\"xsd:string\">6***3</servicecode>");
        xMLcontent.append("<p1 xsi:type=\"xsd:string\">尊敬的客戶,您的驗證碼為:440033</p1>");
        xMLcontent.append("<sendtime xsi:type=\"xsd:string\"></sendtime>");
        xMLcontent.append("      </com:SendSms>");
        xMLcontent.append("   </soapenv:Body>");
        xMLcontent.append("</soapenv:Envelope>");

        //ttpURLConnection(xMLcontent.toString());

        //httpURLConnection(soap12);

        //commonsHttpClient(soap11);
        //commonsHttpClient(soap12);

        String s = httpClient(xMLcontent.toString(), urlWsdl);
        System.out.println(s);
        //httpClient(soap12);


    }
}

 

參考的文章:https://www.cnblogs.com/wuyongyin/p/11899184.html

相關文章