Java HttpURLConnection POST方式調用接口並攜帶兩個參數


花了挺久的時間,看了好多方式,都不行,搞了好久終於解決,現在把代碼貼出來,幫助有需要的人

 

第一步:寫一個調用接口方法

private void updateNotice(String url1, String Message) throws Exception {
        //設置通用的請求屬性
        String[] strings = Message.split(",");
        String json = "{\"id\":\"" + strings[0] + "\",\"copNo\":\"" + strings[1] + "\",\"declareReceipt\":\"正在申報中\",\"declareStatus\":\"2\",\"fileName\":\"CEB621Message" + strings[2] + ".xml\",\"createBy\":\"管理員\"}";
        //簽名
        //規則為id+copno+declarestatus
        //生成的md5字符串規則
        String md5 = strings[0] + strings[1] + "2";
        String md5Encode = DigestUtils.md5Hex(md5).toLowerCase();

        // Post請求的url,與get不同的是不需要帶參數
        URL postUrl = new URL(url1);
        // 打開連接
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        // 設置是否向connection輸出,因為這個是post請求,參數要放在
        // http正文內,因此需要設為true
        connection.setDoOutput(true);
        // Read from the connection. Default is true.
        connection.setDoInput(true);
        // 默認是 GET方式
        connection.setRequestMethod("POST");
        // Post 請求不能使用緩存
        connection.setUseCaches(false);
        //設置本次連接是否自動重定向
        connection.setInstanceFollowRedirects(true);
        // 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的
        // 意思是正文是urlencoded編碼過的form參數
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,
        // 要注意的是connection.getOutputStream會隱含的進行connect。
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection
                .getOutputStream());
        // 正文,正文內容其實跟get的URL中 '? '后的參數字符串一致
        String content = "json=" + URLEncoder.encode(json, "UTF-8") + "&sign=" + URLEncoder.encode(md5Encode, "UTF-8");
        // DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫到流里面
        out.writeBytes(content);
        //流用完記得關
        out.flush();
        out.close();
        //獲取響應
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
        //結束,記得把連接斷了
        connection.disconnect();

    }

第二步:開始調用

public static void main(String[] args) {
    //修改報文狀態及申報信息
    String updateNoticeUrl = "http://127.0.0.1/api/updateNotice";
     try {
           m.updateNotice(updateNoticeUrl, map.get(i + ""));
     } catch (Exception e) {
             e.printStackTrace();
     }
}

 


免責聲明!

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



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