java程序调用http请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/small__snail__5/article/details/88717276

在开发过程中,需要去文件服务器下载歌词文件,将歌词文件流读出并给前端展示,这里做个笔记:

@RequestMapping(value = "/httpString")
    @ResponseBody
    public JSONObject httpString(AccompanyExam accompanyExam) throws Exception{
        JSONObject jsonObject = new JSONObject();
        Integer state = Integer.valueOf(1000);
        String requestUrl = accompanyExam.getLrcLink();
        String result = "http异常";
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);//需要用到输出流
            conn.setDoInput(true);//需要用到输入流
            conn.setRequestProperty("content-type", "text/html");//设置内容类型
            conn.connect();
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            String line;
            int cnt = 0;
            while((line=br.readLine())!=null){  //这里单纯为了前端最后一行歌词不加换行
                if(cnt == 0){
                    buffer.append(line);
                }else{
                    buffer.append("\r\n"+line);
                }
                cnt++;
            }
            result = buffer.toString();
            accompanyExam.setLyricContext(result);
            jsonObject.put("result", accompanyExam); 
        } catch (Exception e) {
            e.printStackTrace();
            state = Integer.valueOf(2000);
            jsonObject.put("msg", e.getCause());
        }
        jsonObject.put("state", state);
        return jsonObject;
    }

猜你喜欢

转载自blog.csdn.net/small__snail__5/article/details/88717276