gpt4 book ai didi

Java-重定向请求

转载 作者:太空宇宙 更新时间:2023-11-04 07:27:15 24 4
gpt4 key购买 nike

我正在用 Java 编写一个 Servlet,基本上,它会在请求正文中获取带有 XML 的请求,然后更改 XML 中的一些内容,并使用新 XML 将请求重定向/前言到位于同一服务器上但位于不同 Web 应用程序上的不同 Servlet。

如何使用新的 XML 重定向/前言请求?我可以在哪里找到代码示例吗?

这是我到目前为止所拥有的:

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String body = getBody(request);
MapXml mapXml = new MapXml(body,
"C:\\Projects\\XmlMapper\\output.xml","C:\\Projects\\XmlMapper\\output\\");
String outputXml = mapXml.getOutputXml();
}
public static String getBody(HttpServletRequest request) throws IOException {
String body = null;
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
return body;
}

我不知道如何从这里继续。我是 servlet 世界的新手..谢谢!干杯:)

最佳答案

如果两个网络应用程序位于同一服务器上,即 Tomcat

in its META-INF/context.xml set <Context crossContext="true" />

getServletContext().getContext("/app").getRequestDispatcher("f.jsp").forward(..);,

其中 app 是另一个应用程序的名称。

或者您可能应该做的是,使用 URLConnection 向任何 URL 发送请求。

URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...

关于请求中如何设置XML,可以在POST请求中携带相对较大量的数据。您还可以找到 POST 数据的最大限制。

just read the bytes that make up the XML file (using FileInputStream) (if you dont have xml in file, use String to create ur xml)and send them in the POST body. Make sure to set the content encoding accordingly.

我正在第四次编辑此内容,以添加更多详细信息。如果您使用Java的HTTP客户端有困难,您可以使用Apache HTTP客户端轻松发布XML。

String xml = "your xml";
PostMethod post = new PostMethod(strURL);
try {
StringRequestEntity requestEntity = new StringRequestEntity(xml);
post.setRequestEntity(requestEntity); ..
....
...

关于Java-重定向请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18355825/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com