概述:
http請求在所有的編程語言中幾乎都是支持的,我們常用的兩種為:GET,POST請求。一般情況下,發送一個GET請求都很簡單,因為參數直接放在請求的URL上,所以,對於PHP這種語言,甚至只需要一行:file_get_content(url);就能完成數據的獲取,但對於POST請求,由於其數據是在消息體中發送出去的,所以相對來說要麻煩一點,再涉及到需要發送文件等二進制的數據類型,就更需要更多的處理,下面我們用Java語言來實現POST請求發送數據,其他語言類似。
public class MainUI { private static final String REQUEST_PATH = "http://localhost/server_url.php"; private static final String BOUNDARY = "20140501"; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub URL url = new URL(REQUEST_PATH); HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); httpConn.setConnectTimeout(3000); // 設置發起連接的等待時間,3s httpConn.setReadTimeout(30000); // 設置數據讀取超時的時間,30s httpConn.setUseCaches(false); // 設置不使用緩存 httpConn.setDoOutput(true); httpConn.setRequestMethod("POST"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)"); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); OutputStream os = httpConn.getOutputStream(); BufferedOutputStream bos = new BufferedOutputStream(os); String content = "--" + BOUNDARY + "\r\n"; content += "Content-Disposition: form-data; name=\"title\"" + "\r\n\r\n"; content += "我是post數據的值"; content += "\r\n--" + BOUNDARY + "\r\n"; content += "Content-Disposition: form-data; name=\"cover_img\"; filename=\"avatar.jpg\"\r\n"; content += "Content-Type: image/jpeg\r\n\r\n"; bos.write(content.getBytes()); // 開始寫出文件的二進制數據 FileInputStream fin = new FileInputStream(new File("avatar.jpg")); BufferedInputStream bfi = new BufferedInputStream(fin); byte[] buffer = new byte[4096]; int bytes = bfi.read(buffer, 0, buffer.length); while (bytes != -1) { bos.write(buffer, 0, bytes); bytes = bfi.read(buffer, 0, buffer.length); } bfi.close(); fin.close(); bos.write(("\r\n--" + BOUNDARY).getBytes()); bos.flush(); bos.close(); os.close(); // 讀取返回數據 StringBuffer strBuf = new StringBuffer(); BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { strBuf.append(line).append("\n"); } String res = strBuf.toString(); System.out.println(res); reader.close(); httpConn.disconnect(); } }
下面,對上述的代碼做一些必要的說明:
http發送的post數據是通過boundary和換行符來分割的,boundary是一個隨機的字符串即可,但不要與你傳遞的參數名或參數值相同。
換行符要求也是比較嚴格的,數據的聲明和數據的值之間需要兩個換行符,兩個數據之間要用boundary來划分。對於二進制的數據來說,只是參數的類型聲明和普通的數據有點區別,比如上述的代碼增加了filename和content-type,二進制的數據以字符流寫出去就行了。