简单 Http 压力测试代码

HttpClient.java

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpClient { private HttpURLConnection http; private String sessionid; public static void main(String[] args) { String url = "http://127.0.0.1:4444/filetest/FileReaderTestServlet.do"; for (int i = 0; i < 10000; i++) { String uid = Util.random(); try { HttpClient client = new HttpClient(); client.openConnection(url); // http://www.baidu.com/s?wd=java client.request("uid=" + uid); client.response(); client.closeConnection(); } catch (IOException e) { e.printStackTrace(); } } } public void openConnection(String httpURL) { try { URL url = new URL(httpURL); http = (HttpURLConnection) url.openConnection(); // http.setRequestMethod("GET"); http.setDoInput(true); http.setDoOutput(true); http.setRequestMethod("GET"); http.setUseCaches(false); http.setInstanceFollowRedirects(false); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http .setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.4) Gecko/20100503 Firefox/3.6.4"); http.setRequestProperty( "Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); http.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5"); http.setRequestProperty("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7"); http.setRequestProperty("Keep-Alive", "115"); http.setRequestProperty("Connection", "keep-alive"); http.setConnectTimeout(500000); if (sessionid != null) { http.setRequestProperty("Cookie", sessionid); } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } /** * @return the sessionid */ public String getSessionid() { return sessionid; } public void request(String data) throws IOException { OutputStream out = null; try { out = http.getOutputStream(); byte[] requsetContent = data.getBytes(); // http // .setRequestProperty("Content-Length", // Integer.toString(requsetContent.length)); out.write(requsetContent); out.flush(); } finally { out.close(); } } public void response() throws IOException { String cks = http.getHeaderField("Set-Cookie"); if (cks != null && sessionid == null) { //System.out.println("Cookie:" + cks); sessionid = cks.substring(0, cks.indexOf(";")); } //System.out.println("header:" + http.getHeaderFields()); /* * for (int i = 1; (key = http.getHeaderFieldKey(i)) != null; i++) { if * (key.equalsIgnoreCase("set-cookie")) { sessionId = * connection.getHeaderField(key); sessionId = sessionId.substring(0, * sessionId.indexOf(";")); } } */ int code = http.getResponseCode(); if (code == HttpURLConnection.HTTP_OK) { InputStream in = null; BufferedReader reader = null; try { in = http.getInputStream(); reader = new BufferedReader(new InputStreamReader(in)); String line = null; System.out.print("接受内容: "); while ((line = reader.readLine()) != null) { System.out.println(new String(line.getBytes(), "UTF-8")); } } finally { reader.close(); // in.close(); } } else { System.out.println("非200 OK! "+http.getResponseCode()); } } public void closeConnection() { http.disconnect(); } }

MainTest.java

import java.io.IOException; public class MainTest implements Runnable { private static String url = "http://127.0.0.1/"; private static long sleepTime = 100; private static int threads = 50; /** * @param args */ public static void main(String[] args) { if (args.length >= 1) { url = args[0]; } if (args.length >= 2) { sleepTime = Long.parseLong(args[1]); } if (args.length >= 3) { threads = Integer.parseInt(args[2]); } System.out.println(""); System.out.println("request URL: " + url); System.out.println("request sleep time(ms): " + sleepTime); System.out.println("request thread num: " + threads); System.out.println(""); Thread[] ts = new Thread[threads]; for (int i = 0; i < threads; i++) { ts[i] = new Thread(new MainTest(), "MainTest-" + i); } for (int j = 0; j < ts.length; j++) { ts[j].start();System.out.println("启动线程:" + ts[j].getName()); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } } public MainTest() { } @Override public void run() { while (true) { String uid = Util.random(); String requestURL=url+Util.genaratePath(uid); //System.out.println(requestURL); try { client.openConnection(requestURL); //client.request("uid=" + uid); client.response(); client.closeConnection(); } catch (IOException e) { e.printStackTrace(); } try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } } } HttpClient client = new HttpClient(); }

Util.java

import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; public class Util { public static final String ROOT_PATH = "D://testData//"; private static String rootPath = ROOT_PATH; public static String saveFilePath = "d:/saveCount/count.csv"; public static void setSaveFilePath(String saveFilePath) { Util.saveFilePath = saveFilePath; if (saveFilePath == null || "".equals(saveFilePath)) { return; } Util.saveFilePath = saveFilePath; } public static void setRootPath(String rootPath) { if (rootPath == null || "".equals(rootPath)) { return; } Util.rootPath = rootPath; } public static boolean read(String filePath) { File file = new File(filePath); if (file.exists()) { return true; } else { return false; } } public static boolean readFile(String filePath) throws FileNotFoundException, IOException { File file = new File(filePath); if (file.exists()) { FileInputStream in = new FileInputStream(file); byte[] b = new byte[1024]; StringBuffer sb = new StringBuffer(); int len = 0; while ((len = in.read(b)) > 0) { // if (len == b.length) { sb.append(b); } else { byte[] temp = new byte[len]; System.arraycopy(b, len, temp, 0, len); sb.append(temp); } } in.close(); return true; } else { return false; } } /** * 创建文件 * * @param filePath * @return */ public static boolean write(String filePath) { File file = new File(filePath); if (file.exists()) { return false; } else { try { System.out.println(file); file.getParentFile().mkdirs(); file.createNewFile(); FileOutputStream out = new FileOutputStream(file); out.write(filePath.getBytes()); out.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } } } }

Count,java

import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; public class Count implements Runnable { private int time = 1; private static AtomicInteger atomic = new AtomicInteger(); private static Date lastDate = new Date(); private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void start(int time) { new Count(time); } private Count(int time) { this.time = time; new Thread(this, "count-queue").start(); } @Override public void run() { String path = Util.saveFilePath; File file = new File(path); file.getParentFile().mkdirs(); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } while (true) { try { lastDate = new Date(); StringBuffer sb = new StringBuffer(format.format(lastDate)); sb.append(","); int count = atomic.get(); sb.append(count); // sb.append(","); // sb.append(getSessionNum()); sb.append("/n"); FileOutputStream out = new FileOutputStream(file, true); out.write(sb.toString().getBytes()); System.out.print("统计信息:" + sb); out.close(); } catch (IOException e) { e.printStackTrace(); } try { Thread.sleep(1000 * 60 * time); } catch (InterruptedException e) { e.printStackTrace(); } } } // public int getSessionNum() { // Context context = (Context) // CountSessionServlet.getContainerWrapper().getParent(); // Session[] temps = context.getManager().findSessions(); // return temps.length; // } public static int increment() { return atomic.incrementAndGet(); } }

CountServlet.java

import java.io.IOException; import java.io.PrintWriter; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.catalina.ContainerServlet; import org.apache.catalina.Wrapper; /** * Servlet implementation class FileReaderTestServlet */ public class FileReaderTestServlet extends HttpServlet { private static final long serialVersionUID = 1L; private int saveTime = 1; private String rootPath; private String saveFilePath; /** * @see HttpServlet#HttpServlet() */ public FileReaderTestServlet() { super(); } /** * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException { rootPath = config.getInitParameter("root"); saveFilePath = config.getInitParameter("saveFilePath"); Util.setRootPath(rootPath); Util.setSaveFilePath(saveFilePath); String time = config.getInitParameter("saveTime"); saveTime = Integer.parseInt(time == null ? "5" : time); Count.start(saveTime); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(true); // System.out.println(session.getId()); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String uid = request.getParameter("uid"); if (uid == null || "".equals(uid)) { out.println("uid 为 空!"); } else { //String path = rootPath + Util.genaratePath(uid); int ct=count.incrementAndGet(); if(ct==10){ count.set(1); } String path="D://testDate2//"+ct+".txt"; boolean success = Util.readFile(path); out.print("读文件:"); out.print(path); if (success) { out.println("成功!"); } else { out.println("失败!"); } } Count.increment(); } private static AtomicInteger count = new AtomicInteger(0); /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值