JAVA 单线程、多线程测试百度网址

JAVA 单线程、多线程访问百度

单线程示例代码

package org.apache.jmeter.functions;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class httpRequestSingle {
    public static void Get(String url_str) {
        try {
            // 创建URL对象
            URL url = new URL(url_str);

            // 创建HttpURLConnection对象,并设置请求方法为GET
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();

            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 打印响应内容
            System.out.println("Response: " + response.toString());

            // 断开连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void Post(String url_str){
        try {
            // 定义请求URL和JSON数据
            String jsonBody = "{\"wd\":\"Java\"}";

            // 创建URL对象
            URL obj = new URL(url_str + "/s");
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 设置请求方法为POST
            con.setRequestMethod("POST");

            // 设置请求头
            con.setRequestProperty("Content-Type", "application/json");

            // 启用输出流,发送请求数据
            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();
            os.write(jsonBody.getBytes());
            os.flush();
            os.close();

            // 获取请求响应
            int responseCode = con.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 输出响应结果
            System.out.println("Response Body: " + response.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        String url = "https://www.baidu.com";       // 读取json文件
        System.out.println("start get====================");
        long startTime = System.currentTimeMillis();
        Get(url);
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        System.out.println("Total time: " + totalTime + "ms");

        System.out.println("start post====================");
        Post(url);


    }
}

在这里插入图片描述

多线程示例代码

package org.apache.jmeter.functions;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class httpRequestMulti {
    private static final String BAIDU_API_URL = "https://www.baidu.com";
    private static final int NUM_REQUESTS = 10; // 并发请求数量
    private static final int TIMEOUT = 5000; // 连接超时时间(毫秒)
    private static long totalResponseTime = 0;

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(NUM_REQUESTS);
        long startTime = System.currentTimeMillis();


        for (int i = 0; i < NUM_REQUESTS; i++) {
            executor.execute(new RequestTask());
        }

        executor.shutdown();
        while (!executor.isTerminated()) {
            // 等待所有任务完成
        }

        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        double averageResponseTime = (double) totalResponseTime / NUM_REQUESTS;

        System.out.println("Total requests: " + NUM_REQUESTS);
        System.out.println("Total time: " + totalTime + "ms");
        System.out.println("Average response time: " + averageResponseTime + "ms");
    }

    private static class RequestTask implements Runnable {
        @Override
        public void run() {
            try {
                long startTime = System.currentTimeMillis();

                URL url = new URL(BAIDU_API_URL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(TIMEOUT);

                // 发送请求并获取响应码
                int responseCode = connection.getResponseCode();

                // 响应成功时,读取响应内容
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    connection.getInputStream();
                }

                connection.disconnect();

                long endTime = System.currentTimeMillis();
                long responseTime = endTime - startTime;

                synchronized (httpRequestMulti.class) {
                    totalResponseTime += responseTime;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值