public static void main(String [] args){try { Map<String,String> map = new HashMap<>(); map.put("param1","324"); map.put("param2","56"); //转化 String json = mapper.writeValueAsString(map); System.out.println("邮件json:" + json); //以上为 //调用 // 设置WebService的WSDL地址 String wsdlUrl = "https://test.edu.cn/mp/service/EmailService"; // 创建URL对象 URL url = new URL(wsdlUrl); //这里解决调用需要证书的问题 TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // 设置请求的数据 String payload = getXml(json); final OutputStream outputStream; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); //这里解决调用需要证书的问题 // 打开连接 HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); // 设置请求方法 connection.setRequestMethod("POST"); // 设置通用的请求属性 connection.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); connection.setRequestProperty("SOAPAction", ""); // 设置输入输出权限,connection默认没有 connection.setDoInput(true); connection.setDoOutput(true); outputStream = connection.getOutputStream(); outputStream.write(payload.getBytes(StandardCharsets.UTF_8)); // 执行发送,获取响应数据 final InputStream inputStream = connection.getInputStream(); final InputStreamReader reader = new InputStreamReader(inputStream); final BufferedReader bufferedReader = new BufferedReader(reader); StringBuilder sb = new StringBuilder(); String temp = null; while (null != (temp = bufferedReader.readLine())) sb.append(temp); System.out.println(sb); bufferedReader.close(); reader.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); }}private static String getXml(String json) { String[] templates = { "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n", "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ema=\"http://email.webservice.com\">\n", " <soapenv:Header/>\n", " <soapenv:Body>\n", " <ema:saveEmail>\n", " <ema:in0>",json,"</ema:in0>\n", " </ema:saveEmail>\n", "</soapenv:Body>\n", "</soapenv:Envelope>\n" }; final StringBuffer buffer = new StringBuffer(); Arrays.asList(templates).forEach(buffer::append); return buffer.toString(); }
通过HttpsURLConnection 调用 webService 接口
于 2024-04-30 10:50:19 首次发布