【发布时间】:2015-08-04 12:30:25
【问题描述】:
我是网络编程的初学者。我使用 Eclipse Java EE 和在 localhost 中运行的 Tomcat 服务器创建了一个应用程序。
应用程序的目标是从客户端获取信息并发送回其他信息。
我开发了一个 servlet 并实现了一个完美运行的 doPost() 方法。我获得了保存在名为 USSDPull 的 bean 中的信息,并将其写入名为 log.txt 的文本文件中。
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
USSDPull ussdpull = new USSDPull();
ussdpull.setUssdstring(request.getParameter("ussdstring"));
ussdpull.setSessionid(Integer.parseInt(request.getParameter("sessionid")));
ussdpull.setMsisdn(request.getParameter("msisdn"));
ussdpull.setUssdcode(request.getParameter("ussdcode"));
ussdpull.setEncoding(Integer.parseInt(request.getParameter("encoding")));
response.setContentType("text/text");
response.setCharacterEncoding( "UTF-8" );
PrintWriter out = response.getWriter();
out.flush();
out.println("POST received : " + ussdpull.getUssdstring()+" "+ussdpull.getSessionid()+" "+ussdpull.getMsisdn()+" "+ussdpull.getUssdcode()+" "+ussdpull.getEncoding());
//WRITE IN FILE
FileWriter fw = new FileWriter("D:/Users/Username/Documents/log.txt", true);
BufferedWriter output = new BufferedWriter(fw);
output.write(dateFormat.format(date)+";"+ussdpull.getUssdstring()+";"+ussdpull.getSessionid()+";"+ussdpull.getMsisdn()+";"+ussdpull.getUssdcode()+";"+ussdpull.getEncoding()+"\n");
output.flush();
output.close();
}
我需要 servlet 将 2 个特定的布尔值和 1 个字符串发送回客户端。我不知道该怎么做。是否可以使用 HttpServletResponse 发送数据?还是我需要找到一种方法来“调用”doGet() 方法?
【问题讨论】:
-
您已经在示例代码中发回了数据(“POST received”等)。你到底有什么问题?
-
我写这个只是为了检查数据。 Println() 是否足以真正发送数据?我以为只是在命令行中显示信息,因为我使用 curl 来模拟交互。基本上,数据来自设备。接下来,数据进入服务并重新发送到我的应用程序。如果我收到所需的信息,我需要从服务器发回数据以告知服务。
-
好吧,您通过获取响应编写器并打印到它来发回字符数据。 Curl 只是显示它得到的响应,如果你在浏览器中运行它,你会看到它是文本。现在由您决定如何发送数据。作为文本表示(甚至可能是 JSON)或作为二进制数据(尽管与您发送的数据量无关)。
-
非常感谢卡亚曼!我将更深入地搜索 JSON 和二进制数据以完成我的应用程序。
标签: java servlets http-post tomcat7 eclipse-jee