【问题标题】:JAVA Send Post Request which contains XML StringJAVA 发送包含 XML 字符串的 Post 请求
【发布时间】:2014-09-26 02:14:03
【问题描述】:

问题描述

我正在尝试编写一个向服务器发送 POST 请求的代码。由于服务器还不存在,我无法测试这部分代码。根据请求,我必须将 XML 作为字符串发送,如下所示:

String XMLSRequest = "<?xml version="1.0" encoding="UTF-8" standalone="no"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header><AuthenticationHeader><Username>Victor</Username><Password>Apoyan</Password></AuthenticationHeader></soapenv:Body></soapenv:Envelope>"

解决方案

String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = String.format("request=%s", XMLSRequest);

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

问题

这是将字符串(类似 XML 的字符串)作为 POST 请求发送到服务器的正确方法吗?

【问题讨论】:

  • 首先您需要序列化为 JSON,然后通过 HTTP 发送。
  • 不知道为什么要将“request=”附加到 XML 中,除了看起来没问题。
  • @RomanC 你能举一些例子来回答如何以正确的方式通过http连接发送XML字符串吗?
  • @kharyam 你的意思是String urlParameters = XMLSRequest; 这可以吗?
  • 你不应该使用http连接。

标签: java xml post xmlhttprequest http-post


【解决方案1】:

要发布SOAP request,您需要将 xml 写入请求正文。您不想将其写为请求的参数。

String url = "https://testurl.com/somerequest";
URL obj = new URL(url);
urlConnection con = (HttpsURLConnection) obj.openConnection();

// add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");

// Send post request
con.setDoOutput(true);
OutputStream os = con.getOutputStream(); //get output Stream from con
os.write( XMLSRequest.getBytes("utf-8") );
os.close();

【讨论】:

  • urlConnection 无法运行我的 jax-rs Web 服务,其中 lib 添加了该服务
猜你喜欢
  • 1970-01-01
  • 2016-03-28
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
相关资源
最近更新 更多