import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
/**
* ClassName: HttpClientTest <br/>
* Function: TODO ADD FUNCTION. <br/>
* @version
* JDK 1.6
*/
public class HttpClientTest {
private static int thread_num = 200; // 线程数
private static int client_num = 500; // 执行程序次数
public static void main(String[] args) {
DefaultHttpClient httpclient = new DefaultHttpClient();
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(thread_num);
for (int index = 0; index < client_num; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println("Thread:" + NO);
/*---------------------具体业务逻辑 begin------------------------*/
String host = "";
HttpPost post = new HttpPost(host);
//配置json参数
JSONObject params = new JSONObject();
params.put("aa", "11");
params.put("bb", "22");
params.put("cc", "33"+NO);
StringEntity s = new StringEntity(params.toString());
//设置编码格式
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/json");
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
//httpstatus = 200
if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
JSONObject response = null;
response = JSONObject.fromObject(result);
//输出返回结果
System.out.println(response.toString());
}
//释放链接
EntityUtils.consume(res.getEntity());
/*---------------------具体业务逻辑 end------------------------*/
semp.release();
} catch (Exception e) {
e.printStackTrace();
}
}
};
exec.execute(run);
}
exec.shutdown();
}
}