1 //發送post請求
2 PrintWriter out = null; 3 BufferedReader in = null; 4 String result = ""; 5 try { 6 URL realUrl = new URL("http:..........................."); 7 // 打開和URL之間的連接
8 URLConnection conn = realUrl.openConnection(); 9 // 設置通用的請求屬性
10 conn.setRequestProperty("accept", "*/*"); 11 conn.setRequestProperty("connection", "Keep-Alive"); 12 conn.setRequestProperty("user-agent", 13 "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); 14 // 發送POST請求必須設置如下兩行
15 conn.setDoOutput(true); 16 conn.setDoInput(true); 17 // 獲取URLConnection對象對應的輸出流
18 out = new PrintWriter(conn.getOutputStream()); 19 // 發送請求參數 20 //參數格式如下
21 out.print("uid="+uid+"&status="+status+"&gender="+gender+"&channel="+u.getChannel()); 22 // flush輸出流的緩沖
23 out.flush(); 24 // 定義BufferedReader輸入流來讀取URL的響應
25 in = new BufferedReader( 26 new InputStreamReader(conn.getInputStream(),"UTF-8")); 27 String line = ""; 28 while ((line = in.readLine()) != null) { 29 result += line; 30 } 31
32 } catch (Exception e) { 33 System.out.println("發送 POST 請求出現異常!"+e); 34 e.printStackTrace(); 35 } 36 //使用finally塊來關閉輸出流、輸入流
37 finally{ 38 try{ 39 if(out!=null){ 40 out.close(); 41 } 42 if(in!=null){ 43 in.close(); 44 } 45 } 46 catch(IOException ex){ 47 ex.printStackTrace(); 48 } 49 } 50 System.out.println(result);