接口测试Java、python分别实现

免token  post请求方式
说明:以下代码实现中是根据我自己的业务逻辑实现,请结合自身实际情况参考使用。

python代码实现:

from ast import For
from email import header
from pyexpat.errors import codes
from time import sleep
from wsgiref.headers import Headers
import requests
import json
from urllib.parse import urlencode
import os
url = ''
headers = {"Content-type":"application/json"}
codesList = []
count = 1
with open(file='F:/Code/VSCode/PythonCode/muyuan/code_list.txt',mode='r',encoding='utf-8') as d:
    file = d.readlines()
    for line in file:
        if count % 1000 == 1:
            codesList.append(','.join(codes))
            codes = []
        codes.append(str(line).strip('\n'))
wr = open(file='F:/Code/VSCode/PythonCode/muyuan/r1.txt',mode='a+',encoding='utf-8')

for codesStr in codesList:
    data = {
    "jobNos": codesStr
    }
    r = requests.post(url=url,headers=headers,data=json.dumps(data))
    for t in r.json()['data']:
        print(f'{t["jobNo"]},{t["leaveDate"]}')
        wr.write(f'{t["jobNo"]},{t["leaveDate"]}\n')
        wr.flush
    wr.flush
    r.close
    sleep(0.5)

Java代码实现:


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.StringUtils;
import com.alibaba.fastjson.JSONObject;

/**
 * @Author: 魏一鸣
 * @Description:
 * @Date 
 * @Modified By:
 */
public class HttpPost1 {


	public static void main1() {
		String srcPath = "";
		String destPath ="";

		BufferedWriter bw = null;
		try {
			 bw = new BufferedWriter(new FileWriter(destPath));

		} catch (IOException e) {
			throw new RuntimeException(e);
		}



		ArrayList<String> codesList = mainRead(srcPath);
		for (String codes : codesList) {
			String data = "{"+"\"jobNos\":"+" \""+codes+"\"}";
			JSONObject jsonObject = JSONObject.parseObject(data);
//			System.out.println("jsonObject="+jsonObject.toString());
		
 			String url = "";
			try {
				String s = httpJson(10000, url, data);
				System.out.println("s="+s);
				JSONObject resJson = JSONObject.parseObject(s);
				JSONArray resJsonJSONArray = resJson.getJSONArray("data");
				for (Object o : resJsonJSONArray) {
					JSONObject dataJson = JSONObject.parseObject(o.toString());
					String result = dataJson.get("jobNo").toString()+","+dataJson.get("leaveDate").toString();
					System.out.println(result);
//					mainWrite(destPath,result);
					bw.write(result+"\n");
					bw.flush();
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}


	//ms超时毫秒,url地址,json入参
	public static String httpJson(int ms,String url,String json) throws Exception{
		String err = "00", line = null;
		StringBuilder sb = new StringBuilder();
		HttpURLConnection conn = null;
		BufferedWriter out = null;
		BufferedReader in = null;
		try{
			conn = (HttpURLConnection) (new URL(url.replaceAll("/","/"))).openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setConnectTimeout(ms);
			conn.setReadTimeout(ms);
			conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
			conn.connect();
			out = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
			out.write(new String(json.getBytes(), "utf-8"));
			out.flush();//发送参数
			int code = conn.getResponseCode();
			if (conn.getResponseCode()==200){
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
				while ((line=in.readLine())!=null)
					sb.append(line);
			}//接收返回值

		}catch(Exception ex){
			err=ex.getMessage();
		}
		try{ if (out!=null) out.close(); }catch(Exception ex){};
		try{ if (in!=null) in.close(); }catch(Exception ex){};
		try{ if (conn!=null) conn.disconnect();}catch(Exception ex){}
		if (!err.equals("00")) throw new Exception(err);
		return sb.toString();
	}



	public static ArrayList<String> mainRead(String srcPath) {
		try {
			BufferedReader br = new BufferedReader(new FileReader(srcPath));//构造一个BufferedReader类来读取文件
			String s = null;
			ArrayList<String> list = new ArrayList<>();
//			String[] str = {};
			ArrayList<String> codesList = new ArrayList<>();
			while((s = br.readLine())!=null){//使用readLine方法,一次读一行
				list.add(s);
				if (list.size()%2000 == 0) {
					Object[] array = list.toArray();
					String join = StringUtils.join(array, ",");
					codesList.add(join);
					list = new ArrayList<>();
				}
//				System.out.println("===========================================");

//				System.out.println("===========================================");

			}

			return codesList;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

	}



	public static void mainWrite(String destPath,String result) {

		try {
			BufferedWriter bw = new BufferedWriter(new FileWriter(destPath));
			bw.write(result+"\n");
			bw.flush();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}


	}



}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魏一鸣*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值