Python批量发送post请求的实现代码
昨天学了一天的Python(我的生产语言是java,也可以写一些shell脚本,算有一点点基础),今天有一个应用场景,就正好练手了。
这个功能之前再java里写过,比较粗糙,原来是在我本机跑的,今天老大要求要随时保持请求,就用Python改写了下,省的又把一个有跟多杂项的jar包传到服务器,省空间又不乱,而且好读。
先附上java代码:
packagexxxxxx.base; importjava.util.Random; importorg.apache.commons.lang3.StringUtils; importhaojianxiang.util.HttpRequest; publicclassCreateFeedbackData{ publicstaticvoidmain(String[]args){ while(true){ try{ Randomr=newRandom(); intsleep=r.nextInt(1200000)+600000; Thread.sleep(sleep); post(); }catch(Exceptione){ e.printStackTrace(); } } } publicstaticvoidpost(){ Stringurl="http://111.111.111.111:8080/xxxx/post"; int[]types={1,2,3,4}; intindex=(int)(Math.random()*types.length); inttype=types[index]; //String[]contents={"-中文测试-,","-EnglishTest-,","~!@#$%^&*()_;:'-\"<>?/|\\-,",""}; String[]contents={"-中文测试-,","-EnglishTest-,","~!@#$%,",""}; StringBuffercontent=newStringBuffer(); content.append("haojianxiangtest:"); for(inti=0;i<10;i++){ intidx=(int)(Math.random()*contents.length); content.append(contents[idx]); } String[]imgs={"/Upload/appUpload/58c7b315cb39f.jpg", "/Upload/appUploa/58cb467a69873.jpg", "/Upload/appUpload/58afff0e99432.png", "/Upload/appUpload/58b545539eb80.jpg", "/Upload/appUpload/58b55d7c9e281.JPG", }; StringBufferimg=newStringBuffer(); for(inti=0;i<(int)(Math.random()*4);i++){ intlucky=(int)(Math.random()*2); if(lucky==1){ intidx=(int)(Math.random()*imgs.length); img.append(imgs[idx]); img.append(","); } } StringimgStr=""; if(StringUtils.isNotBlank(img)){ imgStr=img.substring(0,img.length()-1); } Stringparam="{\"req\":{\"userId\":xxxxxx},"+ "\"data\":{"\"fbType\":"+type+",\"fbContent\":\""+content.toString()+ "\",\"fbPic\":\""+imgStr+"\"}}"; Stringrst=HttpRequest.sendPost(url,param); System.out.println("TIME--"+System.currentTimeMillis()+"result:"+rst); } }
(代码里的参数地址等我已做了隐藏,json格式可能不准确了,无所谓)
接下来上Python代码:
#!/usr/bin/envpython #-*-coding:utf-8-*- importrandom importurllib importurllib.request importtime defpostFeedBack(): url="http://111.111.111.111:8080/xxxx/post" type=int(random.uniform(1,5)) contents=["-中文测试-,","-EnglishTest-,","~!@#$%,",""] content="haojianxiangtest:" foriinrange(0,10): content+=random.choice(contents) img="" imgs=["/Upload/58c7b315cb39f.jpg", "/Upload/58cb467a69873.jpg", "/Upload/58afff0e99432.png", "/Upload/58b545539eb80.jpg", "/Upload/58b55d7c9e281.JPG"] foriinrange(0,3): lucky=int(random.uniform(0,2)) iflucky==1: img+=random.choice(imgs) img+="," img=img[:-1] data="{\"req\":{\"userId\":xxx}," data+="\"data\":{ data+="\"fbType\":" data+=str(type) data+=",\"fbContent\":\"" data+=content data+="\",\"fbPic\":\"" data+=img data+="\"}}" pdata=bytes(data,encoding="utf-8") f=urllib.request.urlopen(url,pdata) result=f.read() result=result.decode('UTF-8') print(result) if__name__=="__main__": whileTrue: st=int(random.uniform(600,1800)) print("sleep:",st) time.sleep(st) postFeedBack()
Python的写法确实很简洁高效(java代码里post的逻辑,我还是调用了自己的一个工具类,实际代码要更多),今后打算把Python作为优先脚本语言,处理简单问题很快。