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());
	        }
	    }
```

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
上次更新: 2024-01-03, 13:22:13
最近更新
01
2023年度总结
01-03
02
MongoDB的简单的常用语法
12-11
03
cetnos7通过nfs共享磁盘文件
11-24
更多文章>