URL url = null; HttpURLConnection httpurlconnection = null; String str =""; try{ //设置代理上外网 //System.getProperties().setProperty("proxySet", "true"); //System.getProperties().setProperty("http.proxyHost", "***.***.***.***"); //System.getProperties().setProperty("http.proxyPort", "80"); //如果需要验证用户 //Authenticator.setDefault(new MyAuthenticator("HOME\\user","password")); url = new URL("http://127.0.0.1:80/***/servlet/test"); httpurlconnection = (HttpURLConnection) url.openConnection(); httpurlconnection.setDoOutput(true); httpurlconnection.setRequestMethod("POST"); httpurlconnection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.0"); httpurlconnection.setRequestProperty("Content-Type","text/xml;charset=UTF-8"); String postStr="*****"; httpurlconnection.getOutputStream().write(postStr.getBytes("UTF-8")); httpurlconnection.getOutputStream().flush(); httpurlconnection.getOutputStream().close(); int code = httpurlconnection.getResponseCode(); InputStream i = httpurlconnection.getInputStream(); byte[] buffer = new byte[51]; ByteArrayOutputStream bo = new ByteArrayOutputStream(); int read = 0; do{ bo.write(buffer, 0, read); read = i.read(buffer, 0, 50); }while(read!=-1); System.out.println(new String(bo.toByteArray(),"UTF-8")); }catch(Exception e){ e.printStackTrace(); } finally{ if(httpurlconnection!=null){ httpurlconnection.disconnect(); }System.out.println("end:"+System.currentTimeMillis()); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { InputStream i = request.getInputStream(); byte[] buffer = new byte[1001]; ByteArrayOutputStream bo = new ByteArrayOutputStream(); int read = 0; do{ bo.write(buffer, 0, read); read = i.read(buffer, 0, 1000); }while(read!=-1); new String(bo.toByteArray(),"UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("***"); out.flush(); out.close(); try {Thread.sleep(3000);} catch (InterruptedException e) {} System.out.println("end:"+System.currentTimeMillis()); }
在httpurlconnection.getResponseCode()时请求被发送,服务器servlet开始执行,
在servlet执行out.flush()时httpurlconnection.getResponseCode()阻塞结束;
在servlet执行out.close()时i.read()阻塞结束,连接已完成,而无需等到servlet的post方法运行完成。