Java中使用HTTP post请求方式请求webService接口

/**
	 *
	 * @param url 接口地址
	 * @param params 请求参数
	 * @return
	 */
	public String getWebServiceData(String url,String params) throws IOException {
		//接受返回报文
		String result = new String();
		URL u = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) u.openConnection();
		conn.setDoInput(true);
		//允许对外输出数据
		conn.setDoOutput(true);
		conn.setUseCaches(false);
		conn.setDefaultUseCaches(false);
		conn.setRequestProperty("Host","*********.com");
		conn.setRequestProperty("Content-Type","text/xml;charset=UTF-8");
		conn.setRequestProperty("SOAPAction","http://*******************Reg");
		conn.setRequestProperty("Content-Length",String.valueOf(params.length()));
		conn.setRequestMethod("POST");
		//定义输出流
		OutputStream output = conn.getOutputStream();
		if(null != params){
			byte[] b = params.getBytes("utf-8");
			//发送soap请求报文
			output.write(b,0,b.length);
			output.flush();
			output.close();
			//定义输入流,获取soap报文
			InputStream input = conn.getInputStream();
			//设置编码格式
			result = IOUtils.toString(input,"UTF-8");
			input.close();
		}
		System.out.println("请求返回报文:" + result);
		return result;
	}

引入的包:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.io.IOUtils;

相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页