根据第三方的接口,使用httpCline原生去进行获取接口数据
String newsString = "http://v.juhe.cn/toutiao/index?type=top&key=036b07fc22289afe7203b2e26a9a211a"; BufferedReader br = null; HttpURLConnection conn = null; URL reqURL = new URL(newsString); conn = (HttpURLConnection) reqURL.openConnection(); conn.setRequestMethod("POST"); // 打开网络通信输入流 InputStream is = conn.getInputStream(); // 通过is创建InputStreamReader对象 InputStreamReader isr = new InputStreamReader(is, "utf-8"); // 通过isr创建BufferedReader对象 br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); line = br.readLine(); } renderJson(sb); if (conn != null) { conn.disconnect(); } if (br != null) { br.close(); }
根据renderJson传到前端进行渲染,下面是ajax请求
//获取新闻头条 $.ajax({ url:'http://localhost:8080/JustDoit/home/getNews', type:'POST', dataType:'JSON', error: function () { alert('获取不到头条'); }, success: function (res) { console.log(res); alert(res); } });
conslole出来是空的
这是为啥呢??各位大佬
项目:JFinal
renderJson(sb) 改成 renderJson(sb.toString())
js 代码:
error: function () 你确定不是与 success: function 平级? 当然这个错误并不影响你的问题