传入接收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();
        }
    }

猜你喜欢

转载自www.cnblogs.com/gongshun/p/10620012.html