【软件测试】测试开发之利用java内置的HttpURLConnection对象发送post请求进行接口测试

package demo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpDemo {

    public static void main(String[] args) {
        HttpDemo demo = new HttpDemo();
        // 通过传递正确的URL和请求正文内容,调用sendPost方法完成post请求
        String postUrl = "http://localhost/guaishounan/index.php/common/login";
        String postData = "username=guaishounan&password=guaishounan";
        String response = demo.sendPost(postUrl, postData);
        System.out.println(response);
    }
    
    public String sendPost(String postUrl, String postData) {
        String body = "", line = "";
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(postUrl);
            urlConnection = (HttpURLConnection) url.openConnection();

            // 设置HTTP请求的各项参数
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setUseCaches(false);
            urlConnection.setInstanceFollowRedirects(false);
            urlConnection.setRequestProperty("Cookie", "");

            // 定义PrintWriter对象,用于将POST请求正文发送给服务器端
            PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
            out.print(postData);
            out.flush();
            
            // 接收服务器端响应,并用字符串变量body来接收
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream(), "UTF-8"));
            while ((line = in.readLine()) != null) {
                body += "\n" + line;
            }
            
            // 关闭输入输出流对象
            in.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        urlConnection.disconnect();
        return body;
    }
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

怪兽男

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

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

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

打赏作者

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

抵扣说明:

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

余额充值