我一直在尝试使用套接字与 tomcat 通信。我正在形成 HTTP 消息并将其写入 outputStream。连接成功建立,但我没有收到任何响应。当我尝试使用相同的消息通过 telnet 连接时,可以得到响应。请在下面找到代码片段并指出我所缺少的。
String text1 = text.getText();
String text2 = text_1.getText();
String address = combo.getText();
System.out.println("Text1 =" + text1 + " Text2 = " + text2 + " Address = "+address);
try{
StringBuilder builder = new StringBuilder();
Socket socket = new Socket("localhost", 8082);
DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//U need to post actual HTTP MESSAGE HERE
StringBuilder requestBuilder = new StringBuilder();
requestBuilder.append("GET").append(SPACE).append(FORWARD_SLASH).append("SayHello").append(FORWARD_SLASH).append("SayHello").append("?")
.append("text1=").append(text1).append("&text2=").append(text2).append(NEWLINE)/*.append(SPACE).append("HTTP/1.1").append(NEWLINE)
.append("accept").append(COLON).append(SPACE).append("text/plain;").append(SPACE).append("text/html").append(NEWLINE)
.append("accept-language").append(COLON).append("en-US").append(NEWLINE)
.append("connection").append(COLON).append("keep-alive").append(NEWLINE)
.append("host").append(COLON).append("localhost").append(NEWLINE)
.append("user-agent").append(COLON).append("MyUCBrowser").append(NEWLINE)
.append("content-length").append(COLON).append("0").append(NEWLINE)
.append("connection-type").append(COLON).append("text/plain").append(NEWLINE)*/;
/*box.setMessage(requestBuilder.toString());
box.open();*/
System.out.println(requestBuilder.toString());
outToServer.writeUTF(requestBuilder.toString());
String tempResp;
while ((tempResp = inFromServer.readLine()) != null) {
builder.append(tempResp);
}
System.out.println(builder.toString().length() > 0 ? builder.toString() : "Anup Kalane!!!");
text_2.setText(builder.toString());
socket.close();
display.dispose();
}
catch (UnknownHostException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
为方便起见,还附加了 servlet……这是非常基本的一个。我只是为了测试目的而创建它。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String text1 = request.getParameter("text1") != null ? request.getParameter("text1") : "NULL";
String text2 = request.getParameter("text2") != null ? request.getParameter("text2") : "NULL";
System.out.println("Hello");
PrintWriter writer = response.getWriter();
writer.write("<HTML><BODY><H1>HELLO\nText1 = "+text1+"\nText2 = "+text2+"</H1></BODY></HTML>");
writer.close();
}