httpclient定时请求实例

1.pom.xml

    <properties>
<slf4j.version>1.7.21</slf4j.version>
<okhttp.version>3.4.2</okhttp.version>
<httpclient.version>4.5.2</httpclient.version>
<logback.version>1.1.7</logback.version>
</properties> <dependencies> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency> <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-ext</artifactId>
<version>1.7.21</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
</dependency> <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency> <dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp.version}</version>
</dependency>

2. 代码

    public void sendGet(String url){

        CloseableHttpClient httpclient = HttpClients.createDefault();

        RequestConfig requestConfig = RequestConfig
.custom()
.setSocketTimeout(1000*60*60*5)
.setConnectTimeout(1000*60*60*5)
.build(); HttpGet httpget = new HttpGet(url);
httpget.setConfig(requestConfig); try {
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
logger.info("response is {}" ,response);
logger.info("entity is {}" ,entity);
logger.info("result is {}" ,EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//response.close();
} }

3.测试

    public static void main(String[] args) throws InterruptedException {
Sample sample=new Sample();
Calendar start=Calendar.getInstance();
start.set(2017, 7, 23); Calendar end=Calendar.getInstance();
end.set(2017, 7, 24);
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd"); while(true){
String startDate=formatter.format(start.getTime());
start.add(Calendar.DAY_OF_MONTH, 1);
String endDate=formatter.format(start.getTime());
String url="http://test.test.com/daily/getDailyAction?startDate="+startDate
+"&endDate="+endDate;
if(start.after(end)){
break;
}else{
sample.sendGet(url);
Thread.sleep(1000*60*2);
}
} }
上一篇:Jmeter 参数化请求实例


下一篇:Java HttpClient伪造请求之简易封装满足HTTP以及HTTPS请求