50,528
社区成员
发帖
与我相关
我的任务
分享
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
public class HttpTimerTest {
public static void sendHttp(String urlStr) {
System.out.println("sendHttp");
try {
URL url = new URL(urlStr);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
int size = httpURLConnection.getContentLength();
byte[] buffer = new byte[size];
byte[] in_b = new byte[size];
int count = 0;
int rbyte = 0;
System.out.println("size=" + size);
InputStream is = httpURLConnection.getInputStream();
while (count < size) { // 循环读取
rbyte = is.read(buffer);
for (int i = 0; i < rbyte; i++) {
in_b[count + i] = buffer[i];
}
count += rbyte;
}
String content = new String(buffer, "UTF-8");
System.out.println(content);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
Timer timer = new Timer();
boolean i = true;
timer.schedule(new URLTask(), 1000, 5000);
while (i) {
System.out.println(i);
try {
int ch = System.in.read();
if (ch - 'c' == 0) {
i = false;
timer.cancel();//使用这个方法退出任务
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
static class URLTask extends TimerTask {
public void run() {
long start = System.currentTimeMillis();
sendHttp("http://localhost:8888/1/1.txt");
//System.out.println("________");
long end = System.currentTimeMillis();
long time = end - start;
System.out.println(time / 1000 + "秒" + time % 1000 + "毫秒");
}
}
}
public static String httpGet(String url) {
String result = null;
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try {
int statusCode = httpClient.executeMethod(getMethod);// 执行getMethod
System.out.println("status: "+statusCode);
if (statusCode != HttpStatus.SC_OK) {
System.out.println(getMethod.getStatusLine());
}
result = getMethod.getResponseBodyAsString();
System.out.println("url: "+url);
System.out.println("result: "+result);
// System.out.println("result: "+new String(result,"utf-8"));
} catch (HttpException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getCause());
} finally {
getMethod.releaseConnection(); // 释放连接
}
return new String(result).trim();
}
int size = httpURLConnection.getContentLength();