参考书籍:httpClient4.1入门教程
测试环境:
server:apache-tomcat-7.0.30
client:HttpClient 4.2.1
测试结果:
1、HTTP1.1默认打开keep-Alive功能。客户端和服务器端均默认自动开启。
默认情况下:
a、单个连接request次数设置为200时仍然有效
b、超时时间设置20s时仍然有效。
2、setHeader("Keep-Alive", "5"); 超时时间通过此方式设置后未发现效果。
3、client段开启并发链接数在700左右时达到最大,提示无法开启新链接,可做为tomcat最大并发数的参考。
package jre.demo;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
class TimePrinter extends Thread {
int pauseTime;
String name;
int count = 1000;
HttpClient mClient = new DefaultHttpClient();
HttpGet mHttpget = new HttpGet("http://10.100.157.172:8080/HelloTomcat/hello");
public TimePrinter(int x, String n) {
pauseTime = x;
name = n;
}
public void run() {
while (count > 0) {
try {
System.out.print("count is : " + count + "\n");
request();
count --;
Thread.sleep(pauseTime);
} catch (Exception e) {
System.out.println(e);
}
}
}
public void request() {
try {
HttpResponse response;
// mHttpget.setHeader("Keep-Alive", "5");
mHttpget.setHeader("Connection", "Keep-Alive");
response = mClient.execute(mHttpget);
HttpEntity entity = response.getEntity();
System.out.print(response.getStatusLine());
if (entity != null) {
System.out.print("content length is :" + entity.getContentLength() + "\n");
System.out.print("content is :" + EntityUtils.toString(entity) + "\n");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
static public void main(String args[]) {
Thread t= new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
TimePrinter tp = new TimePrinter(100, "Guy");
tp.start();
}
}});
t.start();
//
// TimePrinter tp1 = new TimePrinter(100, "Fast Guy");
//
// tp1.start();
//
// TimePrinter tp2 = new TimePrinter(100, "Slow Guy");
//
// tp2.start();
//
// TimePrinter tp3 = new TimePrinter(100, "Slow Guy1");
//
// tp3.start();
//
// TimePrinter tp4 = new TimePrinter(100, "Slow Guy2");
//
// tp4.start();
//
// TimePrinter tp5 = new TimePrinter(100, "Slow Guy3");
//
// tp5.start();
}
}