此方法可作为工具类,如果大家有更好的,欢迎探讨
import java.io.*;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class readHTTPData {
/**
* cuiqingwei-inset date:2022.8.5 for:java读取url中json文件中的json数据
*/
public static String readByUrlData(String url,String open) {
try {
String json = "";
URL urls = new URL(url);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) urls.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(open);
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(), "}");
return jsons.toString();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}