public class DownloadUtil { private static final Logger LOGGER = LoggerFactory.getLogger(DownloadUtil.class); public static String getJsonStringAt(String urlString) { StringBuffer strBuf = new StringBuffer(); try { URL url = new URL(urlString); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = null; while((line = reader.readLine()) != null) { strBuf.append(line + " "); } reader.close(); } catch (MalformedURLException e) { LOGGER.error("[DownloadUtil.getJsonStringAt] 下载文件异常,exp:{}",e); } catch (IOException e) { LOGGER.error("[DownloadUtil.getJsonStringAt] 下载文件异常,exp:{}",e); } return strBuf.toString(); } public static void main(String[] args) { String jsonStr = DownloadUtil.getJsonStringAt("https://blackfish-fb-private-sit.oss-cn-shanghai.aliyuncs.com/fb/t3/MDUzZTVkMTgtYWZmNC00NGE3LTg3YzgtMDZhMThlYzNkM2Zl.json"); System.out.println(jsonStr); } }
一开始读取远程的Json文件总是出现中文乱码,后来在创建InputStreamReader对象时指定了编码格式UTF-8,问题解决了,就是这一句:
new InputStreamReader(conn.getInputStream(), "UTF-8")