Js加载百度热点新闻

Js加载百度热点新闻调用的是神箭手中的百度风云榜实时热点API(免费,频率限制:每500毫秒一次,并发限制:同时请求3个)

 效果图:

Js加载百度热点新闻_第1张图片

 HTML:

Js:

//显示百度热点新闻
$("#ul_hotspot").html("");
$.getJSON("${ctx}/servlet/chooseServlet?fun=hotspotAPI", function(datas){
    if (datas != null) {
        var ulcontent = "
热点新闻
"; $("#ul_hotspot").append(ulcontent); } });

Java:

//返回热点新闻
private void hotspotAPI(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException {
    String appid="XXXXXXXXXXXXXXXXX";
    String httpUrl = "https://api.shenjian.io/";
    String httpArg = "appid="+appid;
    String jsonResult = Request.request(httpUrl, httpArg);
		
    request.setCharacterEncoding("utf-8");
    JSONObject jsonObject = JSONObject.fromObject(jsonResult);
    PrintWriter out = response.getWriter();
    out.write(jsonObject.toString());
    out.close();
}

vo:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;

public class Request {
	
	/**
	* @param urlAll
	* :请求接口
	* @param httpArg
	* :参数
	* @return 返回结果
	*/
	public static String request(String httpUrl, String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?" + httpArg;
		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setRequestProperty("charset", "utf-8");
			connection.setRequestProperty("Accept-Encoding", "gzip");
			connection.connect();
			InputStream is = new GZIPInputStream(connection.getInputStream());
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}

 

你可能感兴趣的:(js)