webservice一般使用cxf或者axios进行webservice请求,不过有时对方系统请求报文格式组装比较复杂,可以使用HttpUrlConnection方式进行请求:
public static String soupHttpConnect() throws Exception { String wsUrl="wldl地址"; //可通过字符串拼接等方式组装 String soapXML="组装的webservice请求格式"; //第一步:创建服务地址,不是WSDL地址 URL url = null; String result=null; try { logger.info("===开始==="); url = new URL(wsUrl); //第二步:打开一个通向服务地址的连接 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); //设置超时时间 connection.setConnectTimeout(5000); connection.setReadTimeout(5000); //第四步:组织SOAP数据,发送请求 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()); result=sb.toString(); is.close(); isr.close(); br.close(); logger.info("===发送成功==="); }else { logger.error("===发送失败,错误码是:"+responseCode); } os.close(); } catch (Exception e) { logger.error("请求发送出错,错误信息:"+e.getMessage()); e.printStackTrace(); e.getStackTrace(); throw e; } return result; }