我正在尝试在HttpURLConnection
中编写一些消息,我试图在Servlet中检索相同的消息。这是两个不同的应用程序。
邮件编写代码 (无异常处理)
public static void formUrlAndWrite()
{
URL url = null;
HttpURLConnection httpConnection = null;
OutputStreamWriter outStream = null;
String host = "http://127.0.0.1:8080/HttpTester";
url = new URL(host);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setAllowUserInteraction(true);
httpConnection.setDefaultUseCaches(false);
outStream = new OutputStreamWriter(httpConnection.getOutputStream());
outStream.write("This is a plain text");
outStream.flush();
}
Servlet代码 (无异常处理)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException
{
BufferedReader reader = null;
PrintWriter out = null;
StringBuffer buffer = new StringBuffer();
try
{
//reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
reader = request.getReader();
int read = 0;
char[] charArray = new char[2000];
while((read=reader.read(charArray))>-1)
{
buffer.append(charArray, 0, read);
}
response.setContentType("text/html");
out = response.getWriter();
out.println("<html><body>");
out.print("<h2> Request Buffer is"+buffer+"</h2>");
out.println("</body></html>");
}
}
这两个应用程序是异步运行的,我没有从servlet获取输出。我的疑问是,如果我运行消息编写应用程序,它将在数据库中写入数据。然后,当我运行servlet时,它是如何获取请求的?可能我在这方面做错了。任何帮助表示赞赏。
我尝试过以下网址,这与我的问题非常相似,但没有帮助。
答案 0 :(得分:1)
如果您无法检索第二个servlet中的任何数据,可能是因为您在某处调用request.getParameter()
/getParameterValues()/getParameterMap()
之类的内容。实际上,这些方法会调用getInputStream()
,您只能读取一次请求的内容。
答案 1 :(得分:0)
我在android中使用过此代码, 它可能对你有帮助,可能不是完整的解决方案
写入服务器
try{
String u="hello";
String p="world";
URL url=new URL("http://localhost:8080/LoginExample/LoginServlet?"+"key1="+u+"&key2="+p);
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
}catch(Exception e)
{
e.printStackTrace();
System.out.println("ERROR IN URL CONNECTION---"+e);
}
ServletPage
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
System.out.println("-----servlet--------------");
// UserBean user = new UserBean();
String uname=request.getParameter("key1");
String password=request.getParameter("key2");
System.out.println("uname ins ervlet==="+uname);
System.out.println("password in servlet==="+password);
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
答案 2 :(得分:-1)
我认为您应该将结果转换为字符串,以便代码与此类似(在Servlet页面中):
String uname=(String)request.getParameter("key1");//cast to string
String password=(String)request.getParameter("key2");//cast to string