simulate POST request

本文探讨了如何在Windows环境下使用不同工具和技术模拟POST请求进行负载测试。介绍了使用C#代码、cURL命令行工具及Postman等应用程序的具体方法。

I'm testing on Windows, trying to simulate POST requests (with different form variables) for load testing. I have tried all kinds of load testing software but failed to get it working.

For GET requests, I know I can just put parameters behind the url

http://www.example.com?id=yyy&t=zzz

But how do I simulate a POST request?

I have a chrome REST Client but I do not know what to put in the headers and data.

Here's what I've tried so far:

class Program
    {
        static void Main(string[] args)
        {

            string viewstateid = "/wEPDwUKLTY3NjEyMzE4NWRkK4DxZpjTmZg/RGCS2s13vkEWmwWiEE6v+XrYoWVuxeg=";
            string eventid ="/wEdAAoSjOGPZYAAeKGjkZOhQ+aKHfOfr91+YI2XVhP1c/pGR96FYSfo5JULYVvfQ61/Uw4pNGL67qcLo0vAZTfi8zd7jfuWZzOhk6V/gFA/hhJU2fx7PQKw+iST15SoB1LqJ4UpaL7786dp6laCBt9ubQNrfzeO+rrTK8MaO2KNxeFaDhrQ0hxxv9lBZnM1SHtoODXsNUYlOeO/kawcn9fX0BpWN7Brh7U3BIQTZwMNkOzIy+rv+Sj8XkEEA9HaBwlaEjg=";

            string username = "user1";
            string password = "ttee";

            string loginbutton = "Log In";

            string URLAuth = "http://localhost/login.aspx";
            string postString = string.Format("VIEWSTATE={0}&EVENTVALIDATION={1}&LoginUser_UserName={2}&LoginUser_Password={3}&LoginUser_LoginButton={4}",viewstateid,eventid, username, password,realm,otp,loginbutton);

            const string contentType = "application/x-www-form-urlencoded";
            System.Net.ServicePointManager.Expect100Continue = false;

            CookieContainer cookies = new CookieContainer();
            HttpWebRequest webRequest = WebRequest.Create(URLAuth) as HttpWebRequest;
            webRequest.Method = "POST";
            webRequest.ContentType = contentType;
            webRequest.CookieContainer = cookies;
            webRequest.ContentLength = postString.Length;
            webRequest.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";
            webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

           webRequest.Referer = "http://localhost/login.aspx";

            StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
            requestWriter.Write(postString);
            requestWriter.Close();

            StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
            string responseData = responseReader.ReadToEnd();
            Console.WriteLine(responseData);
            responseReader.Close();
            webRequest.GetResponse().Close();

        }
    }
share improve this question
 

4 Answers

You can try http://www.hurl.it which is easy to test APIs.

share improve this answer
 
 
How do I post to an internal only running development server with this? –  stryba  Mar 2 at 7:55
 
I'm not sure you can. If you want to test a development API I would suggest using Postman chrome app or if you want to test your API automatically you would have to use some automation tool (for example for PHP you could use Behat) –  Andrew Marcinkevičius  Mar 2 at 9:21
 
Exactly my point. –  stryba  Mar 2 at 10:15

It would be helpful if you provided more information - e.g. what OS your using, what you want to accomplish, etc. But, generally speaking cURL is a very powerful command-line tool I frequently use (in linux) for imitating HTML requests:

For example:

curl --data "post1=value1&post2=value2&etc=valetc" http://host/resource

OR, for a RESTful API:

curl -X POST -d @file http://host/resource

You can check out more information here-> http://curl.haxx.se/


EDITs:

OK. So basically you're looking to stress test your REST server? Then cURL really isn't helpful unless you want to write your own load-testing program, even then sockets would be the way to go. I would suggest you check out Gatling. The Gatling documentation explains how to set up the tool, and from there your can run all kinds of GET, POST, PUT and DELETE requests. 

Unfortunately, short of writing your own program - i.e. spawning a whole bunch of threads and inundating your REST server with different types of requests - you really have to rely on a stress/load-testing toolkit. Just using a REST client to send requests isn't going to put much stress on your server.


More EDITs

So in order to simulate a post request on a socket, you basically have to build the initial socket connection with the server. I am not a C# guy, so I can't tell you exactly how to do that; I'm sure there are 1001 C# socket tutorials on the web. With most RESTful APIs you usually need to provide a URI to tell the server what to do. For example, let's say your API manages a library, and you are using a POST request to tell the server to update information about a book with an id of '34'. Your URI might be 

http://localhost/library/book/34

Therefore, you should open a connection to localhost on port 80 (or 8080, or whatever port your server is on), and pass along an HTML request header. Going with the library example above, your request header might look as follows:

POST library/book/34 HTTP/1.0\r\n
X-Requested-With: XMLHttpRequest\r\n
Content-Type: text/html\r\n
Referer: localhost\r\n
Content-length: 36\r\n\r\n
title=Learning+REST&author=Some+Name

From here, the server should shoot back a response header, followed by whatever the API is programed to tell the client - usually something to say the POST succeeded or failed. To stress test your API, you should essentially do this over and over again by creating a threaded process.

Also, if you are posting JSON data, you will have to alter your header and content accordingly. Frankly, if you are looking to do this quick and clean, I would suggest using python (or perl) which has several libraries for creating POST, PUT, GET and DELETE request, as well as POSTing and PUTing JSON data. Otherwise, you might end up doing more programming than stress testing. Hope this helps!

share improve this answer
 
 
using windows OS, i want to simulate data POSTS for load test, I have tried all kinds of load test, but failed to get it working –  user1663380  Sep 1 '13 at 9:35
 
for localhost it doesn't seem to work –  user1663380  Sep 1 '13 at 9:55
 
would really like to write own program, the question is I am still unable to put the POST parameters successfully in the webrequest in my C# code –  user1663380  Sep 1 '13 at 10:34
 
Well that I might be able to help you with. Essentially, after you open a socket to the url specified in the definitions for your rest server, you will have to construct a http request header with the information. It would help to know what framework, etc. your REST server is built with. And, what type of data do you need to pass? JSON? Or plain text? I would be happy to help however I can, maybe we can use SO's chat feature? –  CRK Sep 1 '13 at 10:44
 
asp .net framework 4, I just want to pass the parameters into the webpage to simulate 50 POST requests/sec with different parameters –  user1663380  Sep 1 '13 at 12:14 

Postman is the best application to test your APIs !

You can import or export your routes and let him remember all your body requests ! :)


https://chrome.google.com/webstore/detail/postman-rest-client-packa/fhbjgbiflinjbdggehcddcbncdddomop

share improve this answer
 

Simple way is to use curl from command-line, for example:

DATA="foo=bar&baz=qux"
curl --data "$DATA" --request POST --header "Content-Type:application/x-www-form-urlencoded" http://example.com/api/callback | python -m json.tool

or here is example how to send raw POST request using Bash shell (JSON request):

exec 3<> /dev/tcp/example.com/80

DATA='{"email": "foo@example.com"}'
LEN=$(printf "$DATA" | wc -c)

cat >&3 << EOF
POST /api/retrieveInfo HTTP/1.1
Host: example.com
User-Agent: Bash
Accept: */*
Content-Type:application/json
Content-Length: $LEN
Connection: close

$DATA
EOF

# Read response.
while read line <&3; do
   echo $line
done
import os import ssl import json import time import logging import platform import subprocess import urllib.error import urllib.request import tempfile, shutil class BaseActions: def __init__(self, config_path=None): self.token = "" self.req_process = "" # 默认路径(库所在目录) current_dir = os.path.dirname(os.path.abspath(__file__)) default_setting_path = os.path.join(current_dir, "setting.json") # 如果外部传入路径,则使用外部的 self.setting_path = config_path if config_path else default_setting_path with open(self.setting_path, "r", encoding="utf-8") as f: config = json.load(f) self.config = config self.username = config["username"] self.ip = config["ip"] self.passwd = config["password"] self.initial_passwd = config["initial_password"] ssl._create_default_https_context = ssl._create_unverified_context self.logger = self.create_file_logger("mouse_simulate", "log.txt") @staticmethod def create_file_logger(logger_name, file_name, level=logging.DEBUG): logger = logging.getLogger(logger_name) logger.setLevel(level) if not logger.handlers: fh = logging.FileHandler(file_name) sh = logging.StreamHandler() formatter = logging.Formatter('[%(asctime)s] %(filename)s:%(lineno)d %(levelname)s %(message)s') fh.setFormatter(formatter) sh.setFormatter(formatter) logger.addHandler(fh) logger.addHandler(sh) return logger def genpasswd(self, passwd): passwdDic = '''yLwVl0zKqws7LgKPRQ84Mdt708T1qQ3Ha7xv3H7NyU84p21BriUWBU43odz3iP4rBL3cD02KZciXTysVXiV8ngg6vL48rPJyAUw0HurW20xqxv9aYb4M9wK1Ae0wlro510qXeU07kV57fQMc8L6aLgMLwygtc0F10a0Dg70TOoouyFhdysuRMO51yY5ZlOZZLEal1h0t9YQW0Ko7oBwmCAHoic4HYbUyVeU3sfQ1xtXcPcf1aT303wAQhv66qzW''' passwdStrDe = "RDpbLfCPsJZ7fiv" SecurePasswd = "" LenStrDe = len(passwdStrDe) LenDic = len(passwdDic) LenPasswd = len(passwd) LenPasswdEncode = max(LenPasswd, LenStrDe) for i in range(LenPasswdEncode): cl = 0xBB cr = 0xBB if i >= LenPasswd: cr = ord(passwdStrDe[i]) elif i >= LenStrDe: cl = ord(passwd[i]) else: cl = ord(passwd[i]) cr = ord(passwdStrDe[i]) index = (cl ^ cr) % LenDic SecurePasswd += passwdDic[index] return SecurePasswd def get(self, req): if not self.token: login_payload = { "login": { "username": self.username, "encrypt_type": "1", "password": self.genpasswd(self.passwd) }, "method": "do" } try: login_json = json.dumps(login_payload) response = urllib.request.urlopen(f'https://{self.ip}/{login_json}') self.token = json.loads(response.read())['stok'] except urllib.error.URLError as e: self.logger.error(f'Login failed: {e.reason}') return "timeout" req = req[1:] if req.startswith('/') else req try: response = urllib.request.urlopen(f'https://{self.ip}/stok={self.token}/{req}') return response.read() except urllib.error.URLError as e: self.logger.error(f'GET request failed: {e.reason}') return "timeout" def post(self, req): if not self.token: login_payload = { "login": { "username": self.username, "encrypt_type": "1", "password": self.genpasswd(self.passwd) }, "method": "do" } try: login_json = json.dumps(login_payload) response = urllib.request.urlopen( f'https://{self.ip}', data=bytes(login_json, encoding='utf8') ) resp_bytes = response.read() #self.logger.info(f'Response:: {resp_bytes}') resp_json = json.loads(resp_bytes) self.token = resp_json['stok'] except urllib.error.URLError as e: self.logger.error(f'Login failed: {e.reason}, {self.ip}') return "timeout" try: #self.logger.debug(f'[发送POST请求] {req}') response = urllib.request.urlopen( f'https://{self.ip}/stok={self.token}/ds', data=bytes(req, encoding='utf8') ) return json.loads(response.read()) except urllib.error.URLError as e: self.logger.error(f'POST request failed: {e.reason}') return "timeout" def initial_post(self, req): if not self.token: login_payload = { "login": { "username": self.username, "encrypt_type": "1", "password": self.genpasswd(self.initial_passwd) }, "method": "do" } try: login_json = json.dumps(login_payload) response = urllib.request.urlopen( f'https://{self.ip}', data=bytes(login_json, encoding='utf8') ) resp_bytes = response.read() #self.logger.info(f'Response:: {resp_bytes}') resp_json = json.loads(resp_bytes) self.token = resp_json['stok'] except urllib.error.URLError as e: self.logger.error(f'Login failed: {e.reason}') return "timeout" try: #self.logger.debug(f'[发送POST请求] {req}') response = urllib.request.urlopen( f'https://{self.ip}/stok={self.token}/ds', data=bytes(req, encoding='utf8') ) return json.loads(response.read()) except urllib.error.URLError as e: self.logger.error(f'POST request failed: {e.reason}') return "timeout" def get_stok(self): login_payload = { "login": { "username": self.username, "encrypt_type": "1", "password": self.genpasswd(self.passwd) }, "method": "do" } try: login_json = json.dumps(login_payload) response = urllib.request.urlopen( f'https://{self.ip}', data=bytes(login_json, encoding='utf8') ) resp_bytes = response.read() #self.logger.info(f'Response:: {resp_bytes}') resp_json = json.loads(resp_bytes) self.token = resp_json['stok'] except urllib.error.URLError as e: self.logger.error(f'Login failed: {e.reason}, {self.ip}') return "timeout" def initial_post_without_token(self, req): try: #self.logger.debug(f'[发送POST请求] {req}') data = json.dumps(req).encode("utf-8") response = urllib.request.urlopen("https://%s" % self.ip, data=data) #response = urllib.request.Request('https://%s'%self.ip, data=req.encode('utf-8')) return json.loads(response.read()) except urllib.error.URLError as e: self.logger.error(f'POST request failed: {e.reason}') return "timeout" def set_resolution(self, width, height): data = json.loads(self.req_process) data['system']['simulate_mouse']['resolution_width'] = str(width) data['system']['simulate_mouse']['resolution_height'] = str(height) self.req_process = json.dumps(data) def enable_mouse_log(self): payload = { "method": "do", "system": {"simulate_mouse": {"status": "open"}} } self.post(json.dumps(payload)) def initial_enable_mouse_log(self): payload = { "method": "do", "system": {"simulate_mouse": {"status": "open"}} } self.initial_post(json.dumps(payload)) def disable_mouse_log(self): payload = { "method": "do", "system": {"simulate_mouse": {"status": "close"}} } self.post(json.dumps(payload)) def simulate_click(self, action, x, y): payload = { "method": "do", "system": { "simulate_mouse": { "status": "simulate_manual", "action": action, "position_x": str(x), "position_y": str(y) } } } self.post(json.dumps(payload)) def initial_simulate_click(self, action, x, y): payload = { "method": "do", "system": { "simulate_mouse": { "status": "simulate_manual", "action": action, "position_x": str(x), "position_y": str(y) } } } self.initial_post(json.dumps(payload)) #req = self.initial_post(json.dumps(payload)) #self.logger.info(f'Response:: {req}') def click_right(self, coord, t=None): x,y = coord self.simulate_click("click_right", x, y) wait_time = t if t is not None else 2 #self.logger.info(f'wait {wait_time} seconds to continue next step') time.sleep(wait_time) def click_left(self, coord_info, t=None): name = None x = y = None # 如果 coord_info 是 ((x,y), "name") if (isinstance(coord_info, tuple) and len(coord_info) == 2 and isinstance(coord_info[0], tuple)): (x, y), name = coord_info # 如果 coord_info 是纯 (x,y) elif isinstance(coord_info, tuple) and len(coord_info) == 2 and all(isinstance(i, int) for i in coord_info): x, y = coord_info name = f"({x},{y})" else: raise ValueError(f"click_left 参数错误: {coord_info}") self.simulate_click("click_left", x, y) wait_time = t if t is not None else 2 self.logger.info(f'----Clicking on [{name}] at ({x}, {y}), wait {wait_time}s...') time.sleep(wait_time) def initial_click_left(self, coord_info, t=None): name = None x = y = None # 如果 coord_info 是 ((x,y), "name") if (isinstance(coord_info, tuple) and len(coord_info) == 2 and isinstance(coord_info[0], tuple)): (x, y), name = coord_info # 如果 coord_info 是纯 (x,y) elif isinstance(coord_info, tuple) and len(coord_info) == 2 and all(isinstance(i, int) for i in coord_info): x, y = coord_info name = f"({x},{y})" else: raise ValueError(f"click_left 参数错误: {coord_info}") self.initial_simulate_click("click_left", x, y) wait_time = t if t is not None else 2 self.logger.info(f'----Clicking on [{name}] at ({x}, {y}), wait {wait_time}s...') time.sleep(wait_time) def input(self, string): payload = { "method": "do", "system": { "simulate_mouse": { "status": "simulate_manual", "action": "keyboard_input", "string": string } } } self.post(json.dumps(payload)) time.sleep(1) def initial_input(self, string): payload = { "method": "do", "system": { "simulate_mouse": { "status": "simulate_manual", "action": "keyboard_input", "string": string } } } self.initial_post(json.dumps(payload)) time.sleep(1) def click_and_input(self, coord_info, string): self.click_left(coord_info) self.input(string) def simulate_scroll(self, direction, step=1): payload = { "method": "do", "system": { "simulate_mouse": { "status": "simulate_manual", "action": "scroll_middle", "direction": direction, "step": str(step) } } } self.post(json.dumps(payload)) def wait(self, seconds): time.sleep(seconds) def ping(self, ip_address): try: # 根据操作系统选择不同的ping命令参数 param = '-n' if platform.system().lower() == 'windows' else '-c' response = subprocess.run(['ping', param, '1', ip_address], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) if response.returncode == 0: self.logger.info(f"----成功 ping 通 {ip_address}:\n{response.stdout}") return True else: self.logger.info(f"----未能 ping 通 {ip_address}") return False except Exception as e: print(f"----执行 ping 命令时发生错误: {e}") return False def _save_config_atomic(self): d = os.path.dirname(self.setting_path) or "." fd, tmp = tempfile.mkstemp(dir=d, prefix=".setting.", suffix=".json") os.close(fd) try: with open(tmp, "w", encoding="utf-8") as f: json.dump(self.config, f, indent=4, ensure_ascii=False) shutil.move(tmp, self.setting_path) finally: if os.path.exists(tmp): os.remove(tmp) def set_config_value(self, key, value, persist=True): self.config[key] = value if key == "ip": self.ip = value if persist: self._save_config_atomic() return value def update_ip(self, new_ip: str, persist=True): # 也可在这里做格式校验 return self.set_config_value("ip", new_ip, persist=persist) 这里面有双击函数吗,没有仿照click_left编写
09-25
这是一个基于AI视觉识别与3D引擎技术打造的沉浸式交互圣诞装置。 简单来说,它是一棵通过网页浏览器运行的数字智慧圣诞树,你可以用真实的肢体动作来操控它的形态,并将自己的回忆照片融入其中。 1. 核心技术组成 这个作品是由三个尖端技术模块组成的: Three.js 3D引擎:负责渲染整棵圣诞树、动态落雪、五彩挂灯和树顶星。它创建了一个具备光影和深度感的虚拟3D空间。 MediaPipe AI手势识别:调用电脑摄像头,实时识别手部的21个关键点。它能读懂你的手势,如握拳、张开或捏合。 GSAP动画系统:负责处理粒子散开与聚合时的平滑过渡,让成百上千个物体在运动时保持顺滑。 2. 它的主要作用与功能 交互式情感表达: 回忆挂载:你可以上传本地照片,这些照片会像装饰品一样挂在树上,或者像星云一样环绕在树周围。 魔法操控:握拳时粒子迅速聚拢,构成一棵挺拔的圣诞树;张开手掌时,树会瞬间炸裂成星光和雪花,照片随之起舞;捏合手指时视线会拉近,让你特写观察某一张选中的照片。 节日氛围装饰: 在白色背景下,这棵树呈现出一种现代艺术感。600片雪花在3D空间里缓缓飘落,提供视觉深度。树上的彩色粒子和白色星灯会周期性地呼吸闪烁,模拟真实灯串的效果。 3. 如何使用 启动:运行代码后,允许浏览器开启摄像头。 装扮:点击上传照片按钮,选择温馨合照。 互动:对着摄像头挥动手掌可以旋转圣诞树;五指张开让照片和树化作满天星辰;攥紧拳头让它们重新变回挺拔的树。 4. 适用场景 个人纪念:作为一个独特的数字相册,在节日陪伴自己。 浪漫惊喜:录制一段操作手势让照片绽放的视频发给朋友。 技术展示:作为WebGL与AI结合的案例,展示前端开发的潜力。
【顶级EI复现】计及连锁故障传播路径的电力系统 N-k 多阶段双层优化及故障场景筛选模型(Matlab代码实现)内容概要:本文提出了一种计及连锁故障传播路径的电力系统N-k多阶段双层优化及故障场景筛选模型,并提供了基于Matlab的代码实现。该模型旨在应对复杂电力系统中可能发生的N-k故障(即多个元件相继失效),通过构建双层优化框架,上层优化系统运行策略,下层模拟故障传播过程,从而实现对关键故障场景的有效识别与筛选。研究结合多阶段动态特性,充分考虑故障的时序演化与连锁反应机制,提升了电力系统安全性评估的准确性与实用性。此外,模型具备良好的通用性与可扩展性,适用于大规模电网的风险评估与预防控制。; 适合人群:电力系统、能源互联网及相关领域的高校研究生、科研人员以及从事电网安全分析、风险评估的工程技术人员。; 使用场景及目标:①用于电力系统连锁故障建模与风险评估;②支撑N-k故障场景的自动化筛选与关键脆弱环节识别;③为电网规划、调度运行及应急预案制定提供理论依据和技术工具;④服务于高水平学术论文复现与科研项目开发。; 阅读建议:建议读者结合Matlab代码深入理解模型构建细节,重点关注双层优化结构的设计逻辑、故障传播路径的建模方法以及场景削减技术的应用,建议在实际电网数据上进行测试与验证,以提升对模型性能与适用边界的认知。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值