计时器+多线程请求数据
由于服务端没有做socket,但又需要 每间隔一段时间 请求一下最新数据 所以就用计时器写了个方法
计时器和多线程配合逻辑上想了好久才调试好
package com.text;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Main {
public static Thread thread =null;
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
/**
* 每间隔30秒执行一次 如果当期线程未执行完毕 则跳过执行http请求
*/
if(null==thread || !thread.isAlive()){
thread = null;
thread = new Thread(new Runnable() {
public void run() {
try {
/**
* 请求数据使用了 HttpClient 请求协议
* 还有一种请求方式为 HttpURLConnection 具体写法就不在这边写了
*/
HttpPost post = new HttpPost("服务器请求地址");
//上传参数 此地方未做加密处理 真正上线的代码此处要加密上传
post.setEntity(new UrlEncodedFormEntity(new ArrayList<NameValuePair>()));
CloseableHttpClient client = HttpClients.createDefault();
RequestConfig config = RequestConfig.custom().setConnectTimeout(15000).setSocketTimeout(15000).build();
post.setConfig(config);
HttpResponse response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code == HttpURLConnection.HTTP_OK) {
/**
* 获取字符串数据
*/
HttpEntity httpEntity = response.getEntity();
//一般这个地方获取的字符串都是加密的,如果明文传过来不安全。加密方式有很多种与服务器保持一致即可
String responseContent = EntityUtils.toString(httpEntity);
/**
* 获取文件流
*/
//InputStream is = response.getEntity().getContent();
//FileOutputStream fos = new FileOutputStream("文件写入地址");
//byte[] buffer = new byte[8192];
//int count = 0;
//while ((count = is.read(buffer)) != -1)
//{
// fos.write(buffer, 0, count);
//}
//fos.close();
//is.close();
}else{
System.out.println("下载失败");
}
}catch (Exception e) {
System.out.println("error"+e.getMessage());
}finally {
}
}
});
thread.start();
}
}
}, 1000, 30000);
}
}