Java Servlet 将表单数据发送到 REST API
Java Servlet send form data to REST API
我有一个简单的 HTML 表单来向 REST API 发送请求。它运行良好,当我提交时,它将表单数据发送到 API 并在浏览器中显示响应。
<form name="theForm" action="localhost:8080/App/rest/consumeForm" method="post">
<input name="userName" value="Bob Smith" /><br/>
<input type="submit" value="submit"/>
</form>
浏览器显示:
{"address": "12 First St.", "city": "Toronto"}
我想捕获响应。有任何想法吗? (没有 ajax 或 javascript,请只是普通的旧 Servlet 或 JSP)
第 2 部分:
我现在 POST 我的表单到我创建的 servlet,它处理来自 REST API 的请求和响应。它工作得很好,但它需要表单数据 URLEncoded。谁知道有没有办法把表单数据转换成这样的字符串,甚至直接把表单数据转换成JSON?
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String userName = "Bob Smith";
String country = "Canada";
String queryString = String.format("userName=%s&country=%s"
,URLEncoder.encode(userName, charset)
,URLEncoder.encode(country, charset)
);
我可以动态构建上面的查询字符串吗?
//// send request
URLConnection connection = new URL("localhost:8080/App/rest/consumeForm").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(queryString.getBytes(charset));
}
//// get response
BufferedReader apiResponse = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("\n\n\nrecieved....");
while ((output = apiResponse.readLine()) != null) {
System.out.println(output);
}
I would like to capture the response. Any ideas?
安装一个 servlet Filter
that handles this. When it receives a request for the REST API endpoint, it can feed an HttpServletResponse
to the next element in the chain that is equipped with any tooling you want. You would probably find HttpServletResponseWrapper
作为一个有用的基础 class 您的自定义工具响应 class。
Filter
实施可能遵循以下原则:
public class ResponseCapturingFilter implements Filter {
private static final String SERVLET_TO_FILTER = "...";
@Override
public void init(ServletConfig config) {
// ...
}
@Override
public void destroy() {
// ...
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (((HttpServletRequest) request).getServletPath().equals(SERVLET_TO_FILTER)) {
response = new MyCapturingResponseWrapper(response);
}
chain.doFilter(request, response);
}
}
要捕获响应文本,您可能希望包装器至少适当地覆盖 getOutputStream()
和 getWriter()
。
事实证明,使用 POST 提交到 servlet 并使用 servlet 与 REST API 通信对我有用。可能有更好的方法,但这对于初级开发人员来说似乎相对干净,可以遵循和维护。 (我仍然对其他选择持开放态度)。
我用表单数据构建一个 queryString(req 是 HttpServletRequest)
String theQueryString="domainId=1";
for(Entry<String, String[]> qsParm:req.getParameterMap().entrySet()) {
theQueryString+="&"+qsParm.getKey()+"="+URLEncoder.encode(req.getParameter(qsParm.getKey()), charset);
}
// set up connection to use as API interaction
URLConnection connection = new URL("localhost:8080/App/rest/consumeForm").openConnection();
connection.setDoOutput(true); // Triggers POST apparently
connection.setRequestProperty("Accept-Charset", java.nio.charset.StandardCharsets.UTF_8.name());
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + java.nio.charset.StandardCharsets.UTF_8.name());
// send request to API via connection OutputStream
try (OutputStream output = connection.getOutputStream()) {
output.write(theQueryString.getBytes(java.nio.charset.StandardCharsets.UTF_8.name())); // this sends the request to the API url
}
// get response from connection InputStream and read as JSON
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonMap = mapper.readTree(connection.getInputStream());
// now the response can be worked with in at least two ways that I have tried
String user1 = jsonMap.get("userName").asText();
String user2 = jsonMap.at("user").getValueAsText();
我有一个简单的 HTML 表单来向 REST API 发送请求。它运行良好,当我提交时,它将表单数据发送到 API 并在浏览器中显示响应。
<form name="theForm" action="localhost:8080/App/rest/consumeForm" method="post">
<input name="userName" value="Bob Smith" /><br/>
<input type="submit" value="submit"/>
</form>
浏览器显示:
{"address": "12 First St.", "city": "Toronto"}
我想捕获响应。有任何想法吗? (没有 ajax 或 javascript,请只是普通的旧 Servlet 或 JSP)
第 2 部分: 我现在 POST 我的表单到我创建的 servlet,它处理来自 REST API 的请求和响应。它工作得很好,但它需要表单数据 URLEncoded。谁知道有没有办法把表单数据转换成这样的字符串,甚至直接把表单数据转换成JSON?
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String userName = "Bob Smith";
String country = "Canada";
String queryString = String.format("userName=%s&country=%s"
,URLEncoder.encode(userName, charset)
,URLEncoder.encode(country, charset)
);
我可以动态构建上面的查询字符串吗?
//// send request
URLConnection connection = new URL("localhost:8080/App/rest/consumeForm").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(queryString.getBytes(charset));
}
//// get response
BufferedReader apiResponse = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("\n\n\nrecieved....");
while ((output = apiResponse.readLine()) != null) {
System.out.println(output);
}
I would like to capture the response. Any ideas?
安装一个 servlet Filter
that handles this. When it receives a request for the REST API endpoint, it can feed an HttpServletResponse
to the next element in the chain that is equipped with any tooling you want. You would probably find HttpServletResponseWrapper
作为一个有用的基础 class 您的自定义工具响应 class。
Filter
实施可能遵循以下原则:
public class ResponseCapturingFilter implements Filter {
private static final String SERVLET_TO_FILTER = "...";
@Override
public void init(ServletConfig config) {
// ...
}
@Override
public void destroy() {
// ...
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (((HttpServletRequest) request).getServletPath().equals(SERVLET_TO_FILTER)) {
response = new MyCapturingResponseWrapper(response);
}
chain.doFilter(request, response);
}
}
要捕获响应文本,您可能希望包装器至少适当地覆盖 getOutputStream()
和 getWriter()
。
事实证明,使用 POST 提交到 servlet 并使用 servlet 与 REST API 通信对我有用。可能有更好的方法,但这对于初级开发人员来说似乎相对干净,可以遵循和维护。 (我仍然对其他选择持开放态度)。
我用表单数据构建一个 queryString(req 是 HttpServletRequest)
String theQueryString="domainId=1";
for(Entry<String, String[]> qsParm:req.getParameterMap().entrySet()) {
theQueryString+="&"+qsParm.getKey()+"="+URLEncoder.encode(req.getParameter(qsParm.getKey()), charset);
}
// set up connection to use as API interaction
URLConnection connection = new URL("localhost:8080/App/rest/consumeForm").openConnection();
connection.setDoOutput(true); // Triggers POST apparently
connection.setRequestProperty("Accept-Charset", java.nio.charset.StandardCharsets.UTF_8.name());
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + java.nio.charset.StandardCharsets.UTF_8.name());
// send request to API via connection OutputStream
try (OutputStream output = connection.getOutputStream()) {
output.write(theQueryString.getBytes(java.nio.charset.StandardCharsets.UTF_8.name())); // this sends the request to the API url
}
// get response from connection InputStream and read as JSON
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonMap = mapper.readTree(connection.getInputStream());
// now the response can be worked with in at least two ways that I have tried
String user1 = jsonMap.get("userName").asText();
String user2 = jsonMap.at("user").getValueAsText();