Java后台模拟发送http的get和post请求,并测试

个人学习使用:谨慎参考

1 Client类

import com.thoughtworks.gauge.Step;
import com.thoughtworks.gauge.Table;
import com.thoughtworks.gauge.TableRow;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by KSC on 2/7/2017.
 */
public class testClient {

    //send get request

    /**
     *
     * @param url destination address
     * @param parametersTable request parameters
     * @return remote response result
     */
    @Step("the get method url is <url> and parameters are <parametersTable>")
    public static String sendGet(String url,Table parametersTable){
        Map<String,String> parameters = new HashMap<>();

        for(TableRow row : parametersTable.getTableRows()){
            String key = row.getCell("name");
            String value = row.getCell("age");
            parameters.put(key,value);
        }
        for (String s: parameters.keySet()){
            System.out.println(s+"\t"+parameters.get(s));
        }

        String result = "";//返回的结果
        BufferedReader in = null;//读取响应的输入流
        StringBuffer sf = new StringBuffer();//存储参数
        String params = "";//编码后的参数

        try{
            if (parameters.size() == 1){
                for(String name : parameters.keySet()){
                    sf.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),"UTF-8")
                    );
                }
                params = sf.toString();
            }else{
                for(String name : parameters.keySet()){
                    sf.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),"UTF-8")
                    ).append("&");
                }
                String tempParams = sf.toString();
                params = tempParams.substring(0,tempParams.length()-1);
                System.out.println(params);
            }

            String fullUrl = url + "?" + params;
            System.out.println(fullUrl);

            //创建URL对象
            URL connUrl = new URL(fullUrl);
            //打开URL链接
            HttpURLConnection httpConn = (HttpURLConnection)connUrl.openConnection();

            // 设置通用属性
            httpConn.setRequestProperty("Accept","*/*");
            httpConn.setRequestProperty("Connection","Keep-Alive");
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");

            //建立实际链接
            httpConn.connect();

            //响应头部的获取
            Map<String,List<String>> headers = httpConn.getHeaderFields();

            System.out.println("==============================");
            //遍历头部所有字段
            for(String key : headers.keySet()){
                System.out.println(key+"\t: \t"+headers.get(key));
            }

            //定义bufferedReader输入流来读取URL的响应,并设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));

            String line = "";//读取返回的内容
            while((line = in.readLine()) != null){
                result  = result+line;
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(in != null){
                    in.close();
                }
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }

        System.out.println("*****************************");
        System.out.println(result);
        System.out.println("==============================");
        return result;
    }

//send post request
@Step("the post method url is <url> and parameters are <parametersTable>")
    public static String sendPost(String url,Table parametersTable){
    Map<String,String> parameters = new HashMap<>();

    for(TableRow row : parametersTable.getTableRows()){
        String key = row.getCell("name");
        String value = row.getCell("age");
        parameters.put(key,value);
    }
    for (String s: parameters.keySet()){
        System.out.println(s+"\t\t"+parameters.get(s));
    }
    System.out.println("---------------------");

        String result = "";
        BufferedReader in = null;
        PrintWriter out = null;//
        StringBuffer sf = new StringBuffer();
        String params = "";

        try{

            if (parameters.size() == 1){
                for(String name : parameters.keySet()){
                    sf.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),"UTF-8")
                    );
                }
                params = sf.toString();
            }else{
                for(String name : parameters.keySet()){
                    sf.append(name).append("=").append(
                            java.net.URLEncoder.encode(parameters.get(name),"UTF-8")
                    ).append("&");
                }
                String tempParams = sf.toString();
                params = tempParams.substring(0,tempParams.length()-1);
            }

            URL connUrl = new URL(url);

            HttpURLConnection httpConn = (HttpURLConnection)connUrl.openConnection();

            httpConn.setRequestProperty("Accept","*/*");
            httpConn.setRequestProperty("Connection","Keep-Alive");
            httpConn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");

            //设置post方式
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

            //获取HttpUrlConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());

            //发送请求参数
            out.write(params);

            //flush(冲洗)输出流中的缓冲
            out.flush();

            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));

            String line = "";
            while((line = in.readLine()) != null){
                result = result+line;
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally{
            try{
                if(out != null){
                    out.close();
                }
                if(in != null){
                    in.close();
                }
            }catch(IOException e){
                e.printStackTrace();
            }
        }

        System.out.println("*****************************");
        System.out.println(result);
        System.out.println("============================");
        return result;
    }

}

  2.测试类

  用自动化测试工具gauge进行测试

Use http request for creating user
=====================
Created by KSC on 2/7/2017

This is an executable specification file which follows markdown syntax.
Every heading in this file denotes a scenario. Every bulleted point denotes a step.

call on url with method get
----------------

tags: get

*the get method url is "http://localhost:8080" and parameters are
|name|age|
|----|---|
|tom|20|
|maike|22|

call on url with method post
---------------------------

tags: post

*the post method url is "https://www.baidu.com/" and parameters are
|name|age|
|----|---|
|marry|20|
|rose|22|

  

时间: 2024-10-14 11:53:17

Java后台模拟发送http的get和post请求,并测试的相关文章

Java 后台模拟POST上传

后台模拟POST上传整合 简介:Java后台模拟post请求,发送参数以及上传文件等方式,适用有些公众API接口的调用. 发送请求 后台 package org.lives.platform.upload.utils; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInpu

jmeter ---模拟发送TCP/UDP/HTTP/FTP等请求包

JMeter安装UDP插件后支持发送UDP协议的请求包,官方介绍安装插件后可以用来测试DNS, NTP, TFTP, Boot servers and many-many other systems. JMeter UDP插件下载地址:http://jmeter-plugins.org/downloads/all/,下载JMeterPlugins-Extras-X.X.X.zip其中包含UDP sampler,下载后解压到apache-jmeter-2.11\lib\ext目录. 替换后重启jm

【转】Jmeter模拟发送TCP/UDP/HTTP/FTP等请求包

JMeter安装UDP插件后支持发送UDP协议的请求包,官方介绍安装插件后可以用来测试DNS, NTP, TFTP, Boot servers and many-many other systems. JMeter UDP插件下载地址:http://jmeter-plugins.org/downloads/all/,下载JMeterPlugins-Extras-X.X.X.zip其中包含UDP sampler,下载后解压到apache-jmeter-2.11\lib\ext目录. 替换后重启jm

Jmeter模拟发送TCP/UDP/HTTP/FTP等请求包

JMeter安装UDP插件后支持发送UDP协议的请求包,官方介绍安装插件后可以用来测试DNS, NTP, TFTP, Boot servers and many-many other systems. JMeter UDP插件下载地址:http://jmeter-plugins.org/downloads/all/,下载JMeterPlugins-Extras-X.X.X.zip其中包含UDP sampler,下载后解压到apache-jmeter-2.11\lib\ext目录. 替换后重启jm

postman:模拟发送一个需要cookie认证的请求

1.chrome 已安装插件intercept. 由于chrome安全的限制,发不出带cookie的请求.如果想要发送带cookie的请求,需要开启Interceptor. 2.chrome 浏览器要设置打开,在运行期间浏览器要一直打开. 3.本人是用fiddler对app的请求进行抓包,也可以使用其他工具.查看headers里的cookie,并复制. (如果是web页面,直接查看chrome中对应页面的Network中Request Header的cookie) 4.将复制的内容填入到post

用java模拟发送post请求

package com.bytestream.practice.demo;import java.io.BufferedReader;import java.io.File;import java.io.FileReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.URL;import java.net.URLConnection;

安卓使用Root权限实现后台模拟全局按键、触屏事件方法(类似按键精灵)

继续在网上搜索安卓按键模拟(其实那时都不知道用什么关键字好了,能想到的关键字都用遍了,但是搜索出来的结果,都是之前提到的那几个依赖源码环境和系统权限的方案).发现有很多介绍ADB调试,向手机发送按键事件的文章.刚好之前做过在Root权限下,用Java调用安卓底层的Linux Shell,然后执行pm指令进行APK的安装卸载.这时我突发奇想,能否用Shell调用ADB指令呢? 于是就进行了尝试,使用Java执行Runtime.getRuntime().exec(“su”).getOutputStr

转:Android随笔之——使用Root权限实现后台模拟全局按键、触屏事件方法(类似按键精灵)

本文转载自CSDN的jzj1993,原文连接:http://blog.csdn.net/jzj1993/article/details/39158865 有时我们需要使用安卓实现在后台模拟系统按键,比如对音量进行调节(模拟音量键),关闭前台正在运行的App(模拟返回键),或者模拟触屏事件.但是对于原生安卓系统而言,后台进程关闭前台进程,甚至模拟用户事件,进而操控整个系统,是不符合系统安全原则的,如果有这样的漏洞被病毒或恶意软件所利用,会非常危险. 由于一些特殊原因,我恰巧需要实现这样的功能,而又

Java爬虫模拟登录——不给我毛概二的H某大学

你的账号访问太频繁,请一分钟之后再试! 从大一开始 就用脚本在刷课 在专业课踢的只剩下一门C#的情况下 活活刷到一周的课 大二开始教务系统多了一个非常**的操作 退课池 and 访问频繁缓冲 难道,我大三下还要去学政治课咩? 虽然学政治不如敲代码 但我想毕业啊 emmmmmm 在量子力学的角度,没有抢上毛概的我只是我本体的一个属性,和我本身没有多大关系,我还是快乐敲代码吧. 0.教务系统后台登录流程 先来看一下后台账号密码在发送给服务器之前做了什么处理 这是文中的JS代码 1 j$(docume