用java http post模拟soapUI调用webservice

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
//需要commons-io的jar包
import org.apache.commons.io.IOUtils;

public class demo {

	public static void main(String[] args) {
		try {
			soapSpecialConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void soapSpecialConnection() throws Exception {
		String s = new String();
		StringBuilder soapHeader = new StringBuilder();
		// soapUI自动生成的request xml路径,写入传入参数
		File file = new File("d:\\1.xml");
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			// 一次读入一行,直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				soapHeader.append(tempString);
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		System.out.println("soapHeader=" + soapHeader);
		// 设置soap请求报文的相关属性
		// url从soapUI的request1的RAW标签的POST获取,url中不要有空格
		String url = "http://10.60.217.86:9527/dji-hrService/services/HrService.HrServiceHttpSoap11Endpoint/HTTP/1.1";
		URL u = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) u.openConnection();
		conn.setDoInput(true);
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setDefaultUseCaches(false);
		// Host,Content-Type,SOAPAction从soapUI的request1的RAW标签的Host,Content-Typ,SOAPActione获取
		conn.setRequestProperty("Host", "10.60.217.86:9527");
		conn.setRequestProperty("Content-Type", "ext/xml;charset=UTF-8");
		conn.setRequestProperty("Content-Length",
				String.valueOf(soapHeader.length()));
		conn.setRequestProperty("SOAPAction",
				"urn:getWorkAttendanceByUidAndDate");
		conn.setRequestMethod("POST");
		// 定义输出流
		OutputStream output = conn.getOutputStream();
		if (null != soapHeader) {
			byte[] b = soapHeader.toString().getBytes("utf-8");
			// 发送soap请求报文
			output.write(b, 0, b.length);
		}
		output.flush();
		output.close();
		// 定义输入流,获取soap响应报文
		InputStream input = conn.getInputStream();
		// 需设置编码格式,否则会乱码
		s = IOUtils.toString(input, "UTF-8");
		input.close();
		System.out.println("输出的xml=" + s);
	}
}

soapUI的request1的RAW标签示意

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值