####【在java后台调用接口,发送http请求获取数据–GET】
public static void initmap(){
//发送http请求获取用于初始化的数据
BufferedReader in = null;
String result="";
try {
System.out.println("正在获取初始化所需数据---");
URL url=new URL("http://localhost:1188/border/website/indexrecord");
// 打开和URL之间的连接
URLConnection connection = url.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
List<Website> websiteList= ResultContent.ResultStringtoList(result);
System.out.println("数据获取成功-----正在初始化----");
for(int i=0;i<websiteList.size();i++){
map.put(websiteList.get(i).getKeynum(),websiteList.get(i).getCounts());
}
System.out.println(map);
System.out.println("计数线程初始化完毕");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("请求初始化所需数据失败++");
e.printStackTrace();
}finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
####【请求数据包含在url中】
public static void TimerUpdatemysql(Long counts,Long keynum){
//发送http请求获取用于初始化的数据
try {
System.out.println("正在更新数据库---");
String updateurl="http://localhost:1188/border/website/updatecounts?counts="+counts+"&keynum="+keynum;
System.out.println(updateurl);
URL url=new URL(updateurl);
// 打开和URL之间的连接
URLConnection connection = url.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
System.out.println("数据已更新");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println("存储数据库失败++");
e.printStackTrace();
}
}