如何使用 HTTP POST 将 XML 请求发布到 URL 并检索响应?
更新 抱歉,我想我的问题不清楚。我想知道如何使用 HttpClient 将 XML 请求发布到 URL或 URLConnection并将响应作为 POST 参数获取并将其显示在网页中。
最佳答案
下面是一个如何使用 java.net.URLConnection
完成此操作的示例:
String url = "http://example.com";
String charset = "UTF-8";
String param1 = URLEncoder.encode("param1", charset);
String param2 = URLEncoder.encode("param2", charset);
String query = String.format("param1=%s¶m2=%s", param1, param2);
URLConnection urlConnection = new URL(url).openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // Triggers POST.
urlConnection.setRequestProperty("accept-charset", charset);
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
OutputStreamWriter writer = null;
try {
writer = new OutputStreamWriter(urlConnection.getOutputStream(), charset);
writer.write(query); // Write POST query string (if any needed).
} finally {
if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {}
}
InputStream result = urlConnection.getInputStream();
// Now do your thing with the result.
// Write it into a String and put as request attribute
// or maybe to OutputStream of response as being a Servlet behind `jsp:include`.
关于java - 在 java 中发布 XML 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2735839/