http協議發送post請求


 

package post;

 
import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.URL;

import java.net.URLConnection;

 

public class DoTest {

   /**

    * 請求連接固定參數

    * @param s 傳參地址

    */

   public static URLConnection getConnection(String s) throws IOException { 

        URL url = new URL(s); 

        URLConnection conn = url.openConnection(); 

        conn.setRequestProperty("Accept", "application/json"); // 設置接收數據的格式 

        conn.setRequestProperty("Content-Type", "application/json"); // 設置發送數據的格式 

        return conn; 

    }

   //請求地址帶接口地址,請求參數是json字符串,舉例如下:

   //請求地址:http://127.0.0.1:8080/test/testone

   //請求參數:{

   //              "testone": "testname1",

   //              "testtwo": "testname2"

   //              }

   /**

    * post請求

    * @param s 傳參地址和接口 

    * @param param 請求參數

    * @return 返回響應結果

    * @throws IOException 拋異常

    */

   public static String reqPost(String s, String param) throws IOException {

        System.out.println("請求地址:"+s); 

        System.out.println("請求參數:"+param);

        String res = ""; 

        URLConnection conn = getConnection(s); // POST要求URL中不包含請求參數 

        conn.setDoOutput(true); // 必須設置這兩個請求屬性為true,就表示默認使用POST發送

        conn.setDoInput(true); 

        // 請求參數必須使用conn獲取的OutputStream輸出到請求體參數 

        PrintWriter out = new PrintWriter(conn.getOutputStream()); // 用PrintWriter進行包裝 

        out.println(param); 

        out.flush(); // 立即充刷至請求體)PrintWriter默認先寫在內存緩存中 

        try// 發送正常的請求(獲取資源)

        {  

            BufferedReader in = new BufferedReader( 

              new InputStreamReader(conn.getInputStream(), "utf-8")); 

            String line; 

            while ((line = in.readLine()) != null) { 

                res += line + "\n"; 

            } 

        } catch (Exception e) { 

            System.out.println("Get Error Occured!"); 

            e.printStackTrace(); 

        } 

        return res; 

    }

}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM