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

 

posted @ 2019-03-29 11:11  1只在路上的程序猿  阅读(2060)  评论(0编辑  收藏  举报