我做了这个实现,将Post消息发送到我的servlet:
String urlParameters = "my_file="+LargeString;
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
String req = "http://localhost:8080/MyServlet1";
URL url = new URL( req );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput( true );
conn.setInstanceFollowRedirects( false );
conn.setRequestMethod( "POST" );
conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty( "charset", "utf-8");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setUseCaches( false );
try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
wr.write( postData );
}
在myServlet1中,我尝试使用以下方法检索此数据:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String mydata_serialized = request.getParameter("my_file");
System.out.println(mydata_serialized);
}
什么都没发生。即使我在System.out.println("Hello");
中打印了doPost
这样的简单消息,也没有任何事情发生。这证明邮件未发送到doPost
我如何才能检索发送的信息?
答案 0 :(得分:-2)
request.getParameter(" my_file")将查看URL本身以选择URL参数。找到my_file的值..不在请求的正文中。
因此您可以使用requestproperty并将其存储在那里..在POST消息中执行:
connection.setRequestProperty(key, value);
然后在doPost()中将其拉回来。
request.getRequestProperty(key);
或者我认为......如果您按原样保留第一个代码并使用
BufferedReader reader = request.getReader();
拉出正文(你将postData的值放在它出现的请求的正文中..所以你必须在doPost()Servlet上读取正文才能将信息拉回来..不是URL字符串