1 package com.jiucool.www.struts.action; 2 3 import java.io.BufferedReader; 4 import java.io.DataOutputStream; 5 import java.io.File; 6 import java.io.FileReader; 7 import java.io.IOException; 8 import java.io.InputStreamReader; 9 import java.net.HttpURLConnection; 10 import java.net.URL; 11 import java.net.URLEncoder; 12 13 public class post_request { 14 public static final String GET_URL = "http://www.cngolon.com/request.action?key=j0r56u2"; 15 public static final String POST_URL = "http://www.cngolon.com/request.action"; 16 //get()請求 17 public static void readContentFromGet() throws IOException { 18 // 拼湊get請求的URL字串,使用URLEncoder.encode對特殊和不可見字符進行編碼 19 String getURL = 20 GET_URL + "&activatecode=" + URLEncoder.encode("中國聚龍", "utf-8"); 21 URL getUrl = new URL(getURL); 22 // 根據拼湊的URL,打開連接,URL.openConnection函數會根據URL的類型, 23 // 返回不同的URLConnection子類的對象,這里URL是一個http,因此實際返回的是HttpURLConnection 24 HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection(); 25 // 進行連接,但是實際上get request要在下一句的connection.getInputStream()函數中才會真正發到 26 // 服務器 27 connection.connect(); 28 // 取得輸入流,並使用Reader讀取 29 BufferedReader reader = new BufferedReader( 30 new InputStreamReader(connection.getInputStream(), "utf-8") 31 ); 32 //設置編碼,否則中文亂碼 33 System.out.println("============================="); 34 System.out.println("Contents of get request"); 35 System.out.println("============================="); 36 String lines; 37 while ((lines = reader.readLine()) != null) { 38 //lines = new String(lines.getBytes(), "utf-8"); 39 System.out.println(lines); 40 } 41 reader.close(); 42 // 斷開連接 43 connection.disconnect(); 44 System.out.println("============================="); 45 System.out.println("Contents of get request ends"); 46 System.out.println("============================="); 47 } 48 //post()請求 49 public static void readContentFromPost() throws IOException { 50 // Post請求的url,與get不同的是不需要帶參數 51 URL postUrl = new URL(POST_URL); 52 // 打開連接 53 HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); 54 // Output to the connection. Default is 55 // false, set to true because post 56 // method must write something to the 57 // connection 58 // 設置是否向connection輸出,因為這個是post請求,參數要放在 59 // http正文內,因此需要設為true 60 connection.setDoOutput(true); 61 // Read from the connection. Default is true. 62 connection.setDoInput(true); 63 // Set the post method. Default is GET 64 connection.setRequestMethod("POST"); 65 // Post cannot use caches 66 // Post 請求不能使用緩存 67 connection.setUseCaches(false); 68 // This method takes effects to 69 // every instances of this class. 70 // URLConnection.setFollowRedirects是static函數,作用於所有的URLConnection對象。 71 // connection.setFollowRedirects(true); 72 // This methods only 73 // takes effacts to this 74 // instance. 75 // URLConnection.setInstanceFollowRedirects是成員函數,僅作用於當前函數 76 connection.setInstanceFollowRedirects(true); 77 // Set the content type to urlencoded, 78 // because we will write 79 // some URL-encoded content to the 80 // connection. Settings above must be set before connect! 81 // 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的 82 // 意思是正文是urlencoded編碼過的form參數,下面我們可以看到我們對正文內容使用URLEncoder.encode 83 // 進行編碼 84 connection.setRequestProperty( 85 "Content-Type", 86 "application/x-www-form-urlencoded" 87 ); 88 // 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成, 89 // 要注意的是connection.getOutputStream會隱含的進行connect。 90 connection.connect(); 91 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 92 // The URL-encoded contend 93 // 正文,正文內容其實跟get的URL中'?'后的參數字符串一致 94 String content = 95 "key=j0r53nmbbd78x7m1pqml06u2&type=1&toemail=cngolon@gmail.com" + 96 "&activatecode=" + 97 URLEncoder.encode("中國聚龍", "utf-8"); 98 // DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫道流里面 99 out.writeBytes(content); 100 out.flush(); 101 out.close(); 102 // flush and close 103 BufferedReader reader = new BufferedReader( 104 new InputStreamReader(connection.getInputStream(), "utf-8") 105 ); 106 //設置編碼,否則中文亂碼 107 String line = ""; 108 System.out.println("============================="); 109 System.out.println("Contents of post request"); 110 System.out.println("============================="); 111 while ((line = reader.readLine()) != null) { 112 //line = new String(line.getBytes(), "utf-8"); 113 System.out.println(line); 114 } 115 System.out.println("============================="); 116 System.out.println("Contents of post request ends"); 117 System.out.println("============================="); 118 reader.close(); 119 connection.disconnect(); 120 } 121 }
HttpURLConnection.connect函數,實際上只是建立了一個與服務器的tcp連接,並沒有實際發送http請求。無論是post還是get,http請求實際上直到HttpURLConnection.getInputStream()這個函數里面才正式發送出去。
在readContentFromPost()中,順序是重中之重,對connection對象的一切配置(那一堆set函數)都必須要在connect()函數執行之前完成。而對outputStream的寫操作,又必須要在inputStream的讀操作之前。這些順序實際上是由http請求的格式決定的。
http請求實際上由兩部分組成,一個是http頭,所有關於此次http請求的配置都在http頭里面定義,一個是正文content,在connect()函數里面,會根據HttpURLConnection對象的配置值生成http頭,因此在調用connect函數之前,就必須把所有的配置准備好。
緊接着http頭的是http請求的正文,正文的內容通過outputStream寫入,實際上outputStream不是一個網絡流,充其量是個字符串流,往里面寫入的東西不會立即發送到網絡,而是在流關閉后,根據輸入的內容生成http正文。
至此,http請求的東西已經准備就緒。在getInputStream()函數調用的時候,就會把准備好的http請求正式發送到服務器了,然后返回一個輸入流,用於讀取服務器對於此次http請求的返回信息。由於http請求在getInputStream的時候已經發送出去了(包括http頭和正文),因此在getInputStream()函數之后對connection對象進行設置(對http頭的信息進行修改)或者寫入outputStream(對正文進行修改)都是沒有意義的了,執行這些操作會導致異常的發生。