Java使用HttpUrlConnection调用webService(wsdl)
首先需要下载工具https://pan.baidu.com/s/1XQ-VubxcPFoqwGm7wierHg
下载成功后解压打开exe程序,在wsdl endpoint中输入你wsdl的地址,点击get,等待一小会后会跳到invoke标签下的界面
点击某个方法,例如上图的login,可以看到右边有userName和password两个参数需要填入,点击填写完后点invoke,此时下面的output就把result显示出来了,这时候点击Request/Response标签,可以看到request的属性、request请求体及response返回内容,这些信息等等代码里会用到,下面开始是Java调用方法。
/** * soap调用webService */ public static String sendSoapPost(String url,String xml,String contentType,String soapAction){ HttpURLConnection conn = null; OutputStream out = null; String returnXml = ""; try{ conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestProperty("Content-Type",contentType); if(null != soapAction){ conn.setRequestProperty("SOAPAction",soapAction); } conn.setRequestMethod("POST"); conn.setConnectTimeout(5000); conn.setDoOutput(true); // 向服务器发送数据 conn.setDoInput(true); // 获取服务端的响应 conn.connect(); out = conn.getOutputStream(); out.write(xml.getBytes("UTF-8")); out.flush(); out.close(); int code = conn.getResponseCode(); String tempString = null; StringBuffer sb = new StringBuffer(); BufferedReader bufferedReader = null; if(code == conn.HTTP_OK){ bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); }else{ bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream(),"UTF-8")); } while((tempString = bufferedReader.readLine()) != null){ sb.append(tempString); } if(null != bufferedReader){ bufferedReader.close(); } //响应报文 returnXml = sb.toString(); }catch (Exception e){ e.printStackTrace(); } return returnXml; }
这个方法四个参数,其中xml参数需要把刚刚得到的请求体复制过来后进行修改,对应你要调用的方法和参数等。url、contentType,soapAction则对应刚刚得到的request属性里的属性名一样的值,调用方法运行就会得到响应结果了。