private void doTest() throws Exception {
URL url = new URL("http://localhost:8080/projectName/servletName");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// 设定请求的方法为"POST",默认是GET
con.setRequestMethod("POST");
// Post 请求不能使用缓存
con.setDefaultUseCaches(false);
con.setUseCaches(false);
// 设置是否向httpUrlConnection输出,因为是post请求所以一下输出的内容被放在http正文中
con.setDoOutput(true);
// 设置是否从httpUrlConnection读入
con.setDoInput(true);
// 测试内容
String req = "Test String!";
// 设置正文数据大小
con.setRequestProperty("Content-Length", String.valueOf(req.length()));
OutputStream out = con.getOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeBytes(req);
dout.flush();
dout.close();
out.close();
// 只有运行该行代码后,以上设置的http请求才被真正的发送给服务器,否则服务器是接受不到任何http请求的!
InputStream in = con.getInputStream();
con.disconnect();
}