Java Post请求参数格式为XML

引言:在对接接口时,接口的请求参数为XML格式,响应结果也为XML,下面介绍两种请求方法:

方法一:

private String invoke(String requestUrl, String requestXml) throws Exception {
	StringBuilder builder = new StringBuilder();
	HttpURLConnection connection = getHttpURLConnection(requestUrl);
	// 输出流
	OutputStream outputStream = connection.getOutputStream();
	outputStream.write(requestXml.getBytes(StandardCharsets.UTF_8));
	outputStream.close();
	// 输入流
	InputStream inputStream = connection.getInputStream();
	InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
	BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

	String line = null;
	while ((line = bufferedReader.readLine()) != null) {
		builder.append(line);
	}

	bufferedReader.close();
	inputStreamReader.close();
	inputStream.close();
	connection.disconnect();

	return builder.toString();
}

/**
 * 获取HttpURLConnection
 */
private HttpURLConnection getHttpURLConnection(String requestUrl) throws Exception {
	URL url = new URL(requestUrl);
	HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	
	connection.setConnectTimeout(3000);
	connection.setReadTimeout(3000);
	
	connection.setDoOutput(true);
	connection.setDoInput(true);
	connection.setUseCaches(false);
	
	connection.setRequestMethod("POST");
	connection.setRequestProperty("accept", "*/*");
	connection.setRequestProperty("connection", "Keep-Alive");
	connection.setRequestProperty("Content-type", "application/xml");	
	return connection;
}

方法二:
引入httpclient依赖

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.13</version>
</dependency>
public static String postXmlRequest(String url, String xml) throws Exception {
	HttpPost post = new HttpPost(url);
	post.setHeader("Content-type", "text/xml");
	post.setEntity(new StringEntity(xml));

	CloseableHttpClient client = HttpClients.createDefault();
	CloseableHttpResponse response = client.execute(post);

	return response.getStatusLine().getStatusCode() == 200 ? EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8) : null;
}

设置xml请求体的编码格式为UTF-8

post.setEntity(new StringEntity(xml, "UTF-8"));
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值