您的位置 首页 java

Java Post请求参数格式为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;
}  

路漫漫其修远兮,吾将上下而求索

译文:在追寻真理方面,前方的道路还很漫长,但我将百折不挠,不遗余力地去追求和探索。

如果您有什么好的想法与方法,欢迎在评论区留言,我们一起讨论~

文章来源:智云一二三科技

文章标题:Java Post请求参数格式为XML,非常实用,建议收藏

文章地址:https://www.zhihuclub.com/184791.shtml

关于作者: 智云科技

热门文章

网站地图