java如何模拟多线程http请求代码
这篇文章将为大家详细讲解有关java如何模拟多线程http请求代码,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
创新互联建站是一家专业从事成都网站设计、成都做网站的网络公司。作为专业网络公司,创新互联建站依托的技术实力、以及多年的网站运营经验,为您提供专业的成都网站建设、网络营销推广及网站设计开发服务!
java模拟http发送请求,第一种是HttpURLConnection发送post请求,第二种是使用httpclient模拟post请求,
实例代码:
package test; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /**java 模拟测试多线程测试http请求 * @author wdh * */ public class ServiceThreadTest implements Runnable{ private String url; private MapparamStr; public ServiceThreadTest(String url, Map paramStr) { super(); this.url = url; this.paramStr = paramStr; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map getParamStr() { return paramStr; } public void setParamStr(Map paramStr) { this.paramStr = paramStr; } @Override public void run() { // http请求实现方式 CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post = new HttpPost(url); RequestConfig config = RequestConfig.custom().setConnectionRequestTimeout(10000).setConnectTimeout(10000) .setSocketTimeout(10000).build(); CloseableHttpResponse response = null; try { List params = setHttpNameValues(paramStr); HttpEntity httpentity=new UrlEncodedFormEntity(params,"utf-8"); post.setEntity(httpentity); post.setConfig(config); response = httpClient.execute(post); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); System.out.println("content:" + content); } catch (Exception e) { e.printStackTrace(); } } private List setHttpNameValues(Map paramMap) { List params = new ArrayList (); for (Entry entry:paramMap.entrySet()){ params.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString())); } return params; } public static void main(String[] args) { //运用java工具类中线程池 ExecutorService pool = Executors.newCachedThreadPool(); for (int i =0;i<2;i++) { //开启俩个线程 String url = "xxxx"; Map paramStr = getHttpParamStr(); pool.execute(new ServiceThreadTest(url,paramStr)); } } public static Map getHttpParamStr() { Map param = new HashMap (); param.put("apiversion", 1); param.put("appversion", "3.6.2"); return param; } }
关于“java如何模拟多线程http请求代码”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
当前名称:java如何模拟多线程http请求代码
转载来于:http://azwzsj.com/article/iippcj.html