在java中发布XML请求

在java中发布XML请求

本文介绍了在java中发布XML请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用HTTP POST向网址发布XML请求并检索回复?

How do I post an XML request to a URL using HTTP POST and retrieve the response?

更新抱歉,我的问题不是清楚我猜。我想知道如何使用或并将响应作为POST参数获取并显示在网页中。

Update Sorry, my question was not clear I guess. I want to know how to post an XML request to an URL using either HttpClient or URLConnection and get the response as a POST parameter and display it in a webpage.

推荐答案

以下是如何使用 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&param2=%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中发布XML请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 06:40