package com.greatmap.internet.estate.utils.dex;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.*;
/**
* @author Lxw
* @version 1.0
* @date 2021/5/18 14:18
*/
public class test {
public static void main(String[] args) throws Exception {
//发送请求,最多等待30秒,
String send_url = "http://www.baidu.com";
String params = "参数";
//10秒后,还没有响应,就处理其他事情
//1,计时器
testTimer();
//2,futer来实现
Callable<String> tast = new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(10 * 1000);
return "success";
}
};
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(tast);
try {
String fu_result = future.get(5, TimeUnit.SECONDS);
System.out.println("fu_result:" + fu_result);
} catch (TimeoutException e) {
System.out.println("fu_result: 链接超时");
//超时后可以做其他事情
} catch (InterruptedException e) {
System.out.println("fu_result: 中断");
} finally {
executorService.shutdown();
}
//3,设置http链接时间
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).setSocketTimeout(10 * 1000).build();
HttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
HttpPost httpPost = new HttpPost(send_url);
StringEntity reqEntity = new StringEntity("params", "uft-8");
httpPost.setEntity(reqEntity);
HttpResponse response = httpClient.execute(httpPost);
String http_result = null;
try (InputStream inputStream = response.getEntity().getContent()) {
byte[] data = readFromInputStream(inputStream);
//接受文件到本地
http_result = new String(data, StandardCharsets.UTF_8);
}catch (Exception e){
System.out.println("出现错误");
}
System.out.println("这个链接后响应:"+http_result);
}
private static byte[] readFromInputStream(InputStream inputStream) throws IOException {
ArrayList<Byte> arr = new ArrayList<>();
//缓存数组
byte[] buffer = new byte[50];
int len;
//读取数据
while ((len = inputStream.read(buffer)) != -1) {
for (int i = 0; i < len; i++) {
arr.add(buffer[i]);
}
}
byte[] src = new byte[arr.size()];
for (int i = 0; i < src.length; i++) {
src[i] = arr.get(i);
}
return src;
}
public static void testTimer(){
Timer time=new Timer();//记录
time.schedule(new TimerTask(){
public void run(){
for(int i=0;i<5;i++){
System.out.println("给"+i+"发送消息:垃圾;第"+(++i)+"条");
}
System.out.println("做坏事了");
}
},3000);
}
}