HttpURLConnection post請求 傳參數

    public static JSONObject post(String urlString, ParamInfo paramInfo) throws Exception {
        URL url = new URL(urlString);
        JSONObject jsonObject = new JSONObject();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // 設置該連接可輸入
        conn.setDoOutput(true); // 設置該連接可輸出
        conn.setRequestMethod("POST"); // 設置請求方式
        conn.setRequestProperty("accept","application/json");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Cache-Control", "no-cache");
        conn.setRequestProperty("User-Agent", "Mozilla/5.0");
        String paramJsonStr = JSON.toJSONString(paramInfo);
//        註釋掉的方法沒成功
//        conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
//        System.out.println(paramJsonStr);
//        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
//        dos.write(paramJsonStr.getBytes("UTF-8"));
//        dos.flush();
//        dos.close();
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        JSONObject paramJSONObj = JSON.parseObject(paramJsonStr);
        Map<String,String> encodedParamMap = new HashMap<>();
        for (Map.Entry entry :paramJSONObj.entrySet() ) {
            encodedParamMap.put((String)entry.getKey(),java.net.URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
        }
        String paramStr = encodedParamMap.entrySet().stream().map(a->a.getKey()+"="+a.getValue()).reduce((a,b)->a+"&"+b).get();
        System.out.println(paramStr);
        PrintWriter pw = new PrintWriter(new BufferedOutputStream(conn.getOutputStream()));
        pw.write(paramStr);
        pw.flush();
        pw.close();

        if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
            //開始處理返回數據
            InputStream inputStream = conn.getInputStream();
            String jsonString = IOUtils.toString(inputStream, "UTF-8");
            inputStream.close();
            jsonObject = JSON.parseObject(jsonString, ServerResponse.class).getData();

        } else {
            throw new Exception(String.format("http request failed,status_code:%d", conn.getResponseCode()));
        }
        conn.disconnect();
        System.out.println(jsonObject);
        return jsonObject;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章