龙空技术网

Java Post请求参数格式为XML,非常实用,建议收藏

编程课堂 876

前言:

而今我们对“xml转为java”都比较看重,看官们都想要学习一些“xml转为java”的相关知识。那么小编在网络上搜集了一些对于“xml转为java””的相关知识,希望同学们能喜欢,小伙伴们快快来了解一下吧!

引言:在对接接口时,接口的请求参数为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转为java