import java.util.concurrent.ExecutorService;java
import java.util.concurrent.Executors;apache
import java.util.concurrent.Semaphore;json
import net.sf.json.JSONObject;app
import org.apache.http.HttpResponse;post
import org.apache.http.HttpStatus;ui
import org.apache.http.client.methods.HttpPost;編碼
import org.apache.http.entity.StringEntity;spa
import org.apache.http.impl.client.DefaultHttpClient;.net
import org.apache.http.util.EntityUtils;線程
/**
* ClassName: HttpClientTest <br/>
* Function: TODO ADD FUNCTION. <br/>
* @version
* @since 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();
}
}