Java网络编程(用Java实现http请求)


前言

平时我们一般写好一个接口,如果想要去测试这个接口对不对,通过会采用工具,比如PostMan或者swagger,其实在Java中,本身就封装了关于Http请求的对象(HttpURLConnection类),我们可以通过这个类去调用我们写好的接口,在调用时,也可以在上层逻辑代码中设置不同的参数(虽然工具也可以做到),但是不妨碍我们去了解了解。



一、请求一个不带参数的接口

public Object request(String requestUrl, String method) throws Exception {
        //创建Url类
        URL url = new URL(requestUrl);
        //创建HttpURLConnection类,由这个类发起Http请求
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        //设置请求参数
        httpURLConnection.setRequestMethod(method);
        httpURLConnection.setDoOutput(true);
        //发起请求建立链接
        InputStream inputStream = httpURLConnection.getInputStream();
        //读取response的返回值
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(bytes))>=0){
            bout.write(bytes,0,len);
        }
        inputStream.close();
        bout.close();
        String respone = new String(bout.toByteArray());
        return respone;
    }


二、请求一个带参数的接口,用GET方式,url传值


1.用outputStream流将参数写入

public Object requestByGetAndParams(String requestUrl, HashMap<String,Object> hashMap) throws Exception{
        URL url = new URL(requestUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setDoOutput(true);
        OutputStream outputStream = httpURLConnection.getOutputStream();
        //拼接参数
        StringBuilder stringBuilderParam = new StringBuilder();
        for (String s : hashMap.keySet()){
            stringBuilderParam.append(s).append("=").append(hashMap.get(s)).append("&");
        }
        String param = stringBuilderParam.toString();
        param = param.substring(0,param.length()-1);
        //将参数写入输出流
        outputStream.write(param.getBytes());
        outputStream.flush();
        InputStream inputStream = httpURLConnection.getInputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(bytes))>=0){
            bout.write(bytes,0,len);
        }
        inputStream.close();
        bout.close();
        String respone = new String(bout.toByteArray());
        return respone;
    }

2、直接拼接在参数后面

 public Object requestByGetAndParams2(String requestUrl, HashMap<String,Object> hashMap) throws Exception{
        //拼接参数
        StringBuilder stringBuilderParam = new StringBuilder();
        for (String s : hashMap.keySet()){
            stringBuilderParam.append(s).append("=").append(hashMap.get(s)).append("&");
        }
        String param = stringBuilderParam.toString();
        param = param.substring(0,param.length()-1);
        //拼接到url
        requestUrl = requestUrl + "?" + param;
        URL url = new URL(requestUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setRequestMethod("GET");
        httpURLConnection.setDoOutput(true);
        InputStream inputStream = httpURLConnection.getInputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(bytes))>=0){
            bout.write(bytes,0,len);
        }
        inputStream.close();
        bout.close();
        String respone = new String(bout.toByteArray());
        return respone;
    }

三、post传值

有时候,后端请求接口带有@RequestBody参数,那么就需要请求体传值,传JSON字符串,传值方法和get差不多,但需要为

httpURLConnection.setRequestProperty("content-type","application/json;charset=UTF-8");

设置类型为JSON格式


public Object requestByGetAndParams(String requestUrl, String param) throws Exception{
        URL url = new URL(requestUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        //设置请求方式,请求参数类型
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("content-type","application/json;charset=UTF-8");
        httpURLConnection.setDoOutput(true);
        OutputStream outputStream = httpURLConnection.getOutputStream();
        //将参数写入输出流,param必须是JSON格式
        outputStream.write(param.getBytes());
        outputStream.flush();
        InputStream inputStream = httpURLConnection.getInputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(bytes))>=0){
            bout.write(bytes,0,len);
        }
        inputStream.close();
        bout.close();
        String respone = new String(bout.toByteArray());
        return respone;
    }

​​​​​​日常使用

日常使用,我们写好接口,可以直接在controller层新建一个main就可以测试接口了,对于dto参数,可以直接将其转换成json字符串,调用方法,就能拿到接口返回的数据啦

 

有兴趣可以去git看一下,可以拉下来直接在上面进行测试

gti地址:​​​​​​​

https://gitee.com/deng-qingyu/http-demo.git

总结

简单的记录一下通过java代码去发起http请求,如果有需求,可以在这代码上面加上读取文件里的参数,循环拼接,多线程并发请求等等。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

i进击的攻城狮

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

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

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

打赏作者

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

抵扣说明:

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

余额充值