java访问webservice

import org.dom4j.VisitorSupport;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ReceSoapService extends VisitorSupport {
//以下为主体部分

    //路径
        private static String urlStr="http://localhost:8080/FoodOrderCCTWebService/FoodOrderCCTWebService.asmx";
        /**
         * @param code 查询值
         * @param userName 用户名(登录时)
         * @param pwd 密码(登录时)
         * @return
         */
        public static void receSoap(String code,String userName,String pwd) throws Exception {
            //服务的地址
            URL wsUrl = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) wsUrl.openConnection();
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");//根据返回的数据类型
            OutputStream os = conn.getOutputStream();

            //请求体  一般只改这地方
            String soap = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                    "<soap:Envelope 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/\">\n" +
                    "  <soap:Body>\n" +
                    "    <GetInfo xmlns=\"http://tempuri.org/\">\n" +
                    "      <method>"+code+"</method>\n" +
                    "      <paramValue>"+userName+"|"+pwd+"</paramValue>\n" +
                    "      <online></online>\n" +
                    "    </GetInfo>\n" +
                    "  </soap:Body>\n" +
                    "</soap:Envelope>";

            os.write(soap.getBytes());
            try {
                InputStream is = conn.getInputStream();
                byte[] b = new byte[1024];
                int len = 0;
                String s = "";
                while ((len = is.read(b)) != -1) {
                    String ss = new String(b, 0, len, "UTF-8");
                    s += ss;
                }
                is.close();
                os.close();
                conn.disconnect();

                //输出返回的xml数据
                System.out.println(s);
                //根据需求解析xml,我这里没写,有需求的另外再找吧

            } catch (Exception e) {
                System.out.println("异常:" + e.getMessage());
            }
        }

}

使用这种方法可以较为方便,也比较直观,网上找到的方法感觉不太友好,而且还有区分什么的。

posted @ 2018-04-13 15:19  Teler  阅读(85)  评论(0)    收藏  举报