傳入接收POST請求的接口地址,以及接口需要的JSON參數獲取返回的JSON信息


/**
     * 往指定的URL發送POST請求。
     * @param url
     * @param content
     * @return
     * @throws IOException
     */
    public static String sendMessage(String url,String content) throws IOException{
        URL uRL;
        HttpURLConnection conn;
        OutputStream outputStreamWriter = null;
        BufferedReader bufferedReader = null;
        try {
            uRL = new URL(url); 
            conn = (HttpURLConnection)uRL.openConnection();
            //設置連接超時。
            conn.setConnectTimeout(ContextUtil.getConnectTimeout());
            //設置讀取超時。
            conn.setReadTimeout(ContextUtil.getReadTimeout());
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true)
            conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");
       byte[] sendContents = content.getBytes("utf-8");
 conn.setRequestProperty("Content-Length",String.valueOf(sendContents.length)); conn.setRequestProperty("User-Agent",""); outputStreamWriter=conn.getOutputStream(); outputStreamWriter.write(sendContents, 0, sendContents.length); outputStreamWriter.flush(); outputStreamWriter.close(); bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer response = new StringBuffer(); String line; while((line = bufferedReader.readLine()) != null){ response.append(line); } String result = response.toString(); return result; } catch (MalformedURLException e) { return ""; } catch (IOException e) { String msg=ExceptionUtils.getStackTrace(e); log.error(msg); return ""; } finally{ if(outputStreamWriter!=null) outputStreamWriter.close(); if(bufferedReader!=null) bufferedReader.close(); } }

 


免責聲明!

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



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