有時候需要遠程從其他接口中獲取json數據,如果遇到返回的json數據是一個文件而不直接是數據,那么可以通過以下方法進行讀取:
/** * 從數據接口獲取到數據 * @return * @throws Exception */ public String readData() throws Exception { //創建StringBuffer類型的變量json,用於存放拼裝好的json數據 //StringBuffer json = new StringBuffer(""); String json = ""; //url中不可以出現空格,空格全部用%20替換 String url = "http://192.168.1.190:8888/api/CityData/GetMonitorData?apikey=?&startTime=2017-03-12%2012:00:00&endTime=2017-03-14%2012:00:00&uCode=?&pCode=?,?,?,?,?&datatype=?&isSrc=?"; URL urls = new URL(url); java.net.HttpURLConnection conn = (java.net.HttpURLConnection)urls.openConnection(); //因為服務器的安全設置不接受Java程序作為客戶端訪問,解決方案是設置客戶端的User Agent conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); conn.setDoOutput(true);
conn.setDoInput(true); //只可以設置為GET方式,不可以使用POST方式 //conn.setRequestMethod("POST"); conn.setRequestMethod("GET");
//設置編碼格式為UTF-8
conn.setRequestProperty("contentType", "UTF-8");
//得到輸入流 InputStream inputStream = conn.getInputStream(); //從輸入流中獲取數據(一定要設置編碼格式,不然在服務器端接收到的數據可能亂碼) BufferedReader bf=new BufferedReader(new InputStreamReader(inputStream,"UTF-8")); String line=null; while((line=bf.readLine())!=null){//一行一行的讀 json = json + line; } if(inputStream!=null){ inputStream.close(); } String[] strs = json.split("\\\\"); String str = ""; StringBuffer jsons = new StringBuffer(""); for (int i = 0; i < strs.length; i++) { str = strs[i]; jsons = jsons.append(str); } jsons.replace(0, 1, ""); jsons.replace(jsons.length()-1, jsons.length(), ""); this.jsonObject = jsons.toString(); return JSON; }