1. 程式人生 > 其它 >java功能-傳送http請求

java功能-傳送http請求

一、傳送json

    public void test() throws IOException {
        //引數封裝------------------------------------------------------
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        Map<String, Object> params1 = new HashMap<String, Object>();
        List<Object> params2=new
ArrayList<>(); //封裝params1 //封裝params2 //封裝jsonMap jsonMap.put("sendBasic", params1); jsonMap.put("toUsers", params2); String json = JSON.toJSONString(jsonMap); //---建立連線--------------------------------------------------------------- URL url = new
URL("http://");//請求的路徑 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); // 設定可輸入 connection.setDoOutput(true); // 設定該連線是可以輸出的 connection.setRequestMethod("POST");// 設定請求方式 connection.setRequestProperty("Charset", "UTF-8"); connection.setRequestProperty(
"Accept-Charset", "utf-8"); connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); //傳送引數--------------------------------------------------------------------------- BufferedOutputStream pw = new BufferedOutputStream(connection.getOutputStream()); //傳送內容轉碼utf-8 **必寫** pw.write(json.getBytes("UTF-8")); pw.flush(); pw.close(); //讀取響應資料--------------------------------------------------------------------------- //輸入流轉碼utf-8 **必寫** BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line = null; StringBuilder result = new StringBuilder(); while ((line = br.readLine()) != null) { // 讀取資料 result.append(line + "\n"); } }