java 发送 http 请求

public class VoteHandler implements IVoteHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(RecorduvpvHandler.class);

    @Override
    public void invoke() {
        final String postUrl = "http://localhost:8080/v1/vote/taskEnableControlVote";
        BufferedReader bufferedReader = null;
        try {
            URL url = new URL(postUrl);
            // 打开和url之间的链接
            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            // 设置请求属性
            conn.setRequestProperty("connection", "Keep-Alive");

            conn.setDoOutput(true);
            conn.setDoInput(true);

            // Set the post method. Default is GET
            conn.setRequestMethod("POST");
            // Post cannot use caches
            // Post 请求不能使用缓存
            conn.setUseCaches(false);

            // 定义BufferedReader输入流来读取url相应

            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

            String line;
            String result = "";
            while ((line = bufferedReader.readLine()) != null) {
                result += line;
            }
            LOGGER.info("请求响应结果:"+ JSON.toJSONString(result));
        }catch (Exception e){
            LOGGER.info("请求异常:"+e.getMessage());
        }

        finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            }catch (Exception e){
                LOGGER.info("流关闭异常:"+e.getMessage());
            }
        }
    }
}

  

原文地址:https://www.cnblogs.com/huntaheart/p/5147558.html