我正在尝试使用URL包设置对Spring服务的基本调用,以便我可以通过POST而不是获取它。
客户端代码(调用spring服务的代码):
String data = URLEncoder.encode("testStringFromGWT", "UTF-8") + "=" + URLEncoder.encode(message, "UTF-8");
URL url = new URL("http://localhost:8080/spring-hibernate-mysql/test/test1");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
Spring服务:
@RequestMapping(value = "/test1", method = RequestMethod.POST)
public String loggedInUniversal_logout(
Model model,
HttpServletRequest request,
@RequestParam(value = "inputString", required = true) String inputString)
throws InterruptedException {
HttpSession session = request.getSession();
System.out.println("Request made from Client..." + inputString);
model.addAttribute("token", "It works");
return "token";
}
当我尝试这个时,我得到:
java.io.FileNotFoundException: http://localhost:8080/spring-hibernate-mysql/test/test1
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1401)
我不太确定我做错了什么,我能够确认调用是否正确传递给Spring,因为我可以看到正在打印的行"Request made from Client..." + inputString
但是后来我得到了FileNotFoundException客户端。我通过查看教程拼凑了这些,所以我想我在这里遗漏了一些东西,不胜感激任何建议。
答案 0 :(得分:1)
在尝试从上面示例中的输入流中读取之前关闭输出流。
作为替代方案,请使用http客户端库,例如HTTPClient或Resty。
使用Resty,您的客户端代码将如下所示:
Resty r = new Resty();
String result = r.text(url).toString();
获取GET 并使用简单的表格进行POST:
r.text(url,form(yourformdata)).toString();
免责声明:我是Resty的作者