1. 程式人生 > >java 傳送http協議的POST請求獲取資料

java 傳送http協議的POST請求獲取資料

        /**
	 * @功能  http向指的URL傳送POST請求
	 * @author you
	 * @param method 請求方法,POST
	 * @param url 請求的路徑
	 * @return
	 */ 
	
	   public static String getDataByHttpRequest(String urlPath,String requestMethod){
		   
		   String result=null;
		   //初始化出的StringBuffer物件是一個空的物件
		   StringBuffer buffer=new StringBuffer();
		   PrintWriter out = null;
		   BufferedReader in = null;
		   try
		{
			// 建立連結
			URL httpUrl=new URL(urlPath);
			// 開啟和URL之間的連線
			HttpURLConnection httpConn=(HttpURLConnection)httpUrl.openConnection();
			// 設定通用的請求屬性
			 httpConn.setUseCaches(false);  //不允許快取
			// 傳送POST請求必須設定如下兩行
			httpConn.setDoOutput(true);   //需要輸出
		    httpConn.setDoInput(true);   //需要輸入
		   //設定POST方式連線
		    httpConn.setRequestMethod(requestMethod); 
		    httpConn.setRequestProperty("accept", "*/*");
		    // 維持長連線
		    httpConn.setRequestProperty("connection", "Keep-Alive");
		    httpConn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		    httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		    httpConn.setRequestProperty("Charset", "UTF-8"); 
		    httpConn.connect();
		    
		   // 獲取URLConnection物件對應的輸出流
		    out=new PrintWriter(httpConn.getOutputStream());
		    //flush輸出流的緩衝
            out.flush();
            // 取得url輸入流
            InputStream inputStream = httpConn.getInputStream();  
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");  
            in = new BufferedReader(inputStreamReader); 
            String line;
            while ((line = in.readLine()) != null) {
            	buffer.append(line); 
            }
            // 釋放資源  
            inputStream.close();
            
            result=buffer.toString();
            System.out.println("result---->"+result);
		} catch (Exception e)
		{
			System.out.println("傳送 POST 請求出現異常!"+e);
            e.printStackTrace();
		}
		 //使用finally塊來關閉輸出流、輸入流
	        finally{
	            try{
	                if(out!=null){
	                    out.close();
	                }
	                if(in!=null){
	                    in.close();
	                }
	            }
	            catch(IOException ex){
	                ex.printStackTrace();
	            }
	        }   
		   
		   return result;
	   }

     2.呼叫getDataByHttpRequest方法