0
点赞
收藏
分享

微信扫一扫

Http学习之使用HttpURLConnection…


post请求的OutputStream实际上不是网络 流,而是写入内存,在getInputStream 中才真正把写道流里面的内容作为正文与 根据之前的配置生成的http request头合并成真正的http  request,并在此时才真正向服务器发送。

函数可以改变这个模式,设置了ChunkedStreamingMode后,不再等待OutputStream关闭后生成完整的http request一次过发送,而是先发送http r equest头,正文内容则是网路流的方式实时传送到服务 器。实际上是不告诉服务器http正文的长度, 这种模式适用于向服务器传送较大的 或者是不容易 获取长度的数据,如文件。下 面以一段代码讲解一下,请与 Http学习之使用HttpURLConnection发送post和get请求 中的readContentFromPost()函数作对比:


Http学习之使用HttpURLConnection…_post请求

   

public
   
   static
   
   void
   readContentFromChunkedPost() 
   throws
   IOException 
   {
         URL postUrl =newURL(POST_URL);
         HttpURLConnection connection =(HttpURLConnection) postUrl
                 .openConnection();
         connection.setDoOutput(true);
         connection.setDoInput(true);
         connection.setRequestMethod("POST");
         connection.setUseCaches(false);
         connection.setInstanceFollowRedirects(true);
         connection.setRequestProperty("Content-Type",
                 "application/x-www-form-urlencoded");
         
         connection.setChunkedStreamingMode(5);
         connection.connect();
         
         DataOutputStream out =newDataOutputStream(connection
                 .getOutputStream());
         String content ="firstname="+URLEncoder.encode("一个大肥人                                                                               "+
                 "                                         "+
                 "asdfasfdasfasdfaasdfasdfasdfdasfs", "utf-8");
         out.writeBytes(content); 

         out.flush();
         out.close(); //到此时服务器已经收到了完整的http request了,而在readContentFromPost()函数里,要等到下一句服务器才能收到http请求。
       BufferedReader reader =newBufferedReader(newInputStreamReader(
                 connection.getInputStream()));
         
         out.flush();
         out.close(); //flush and close
       String line;
         System.out.println("=============================");
         System.out.println("Contents of post request");
         System.out.println("=============================");
         while((line =reader.readLine()) !=null) {
             System.out.println(line);
         }
         System.out.println("=============================");
         System.out.println("Contents of post request ends");
         System.out.println("=============================");
         reader.close();
         connection.disconnect();
     }

举报

相关推荐

0 条评论