Java基础系列:HttpURLConnection请求GET、POST接口

1 简介

Java请求Http接口常用的方式有三种,如下表

序号工具描述应用案例
1URLConnectionJava原生,java.net.URLConnectionhttps://blog.csdn.net/Xin_101/article/details/122440247
2HttpURLConnectionJava原生,java.net.HttpURLConnectionhttps://blog.csdn.net/Xin_101/article/details/122449254
3httpclient第三方工具,org.apache.httpcomponentshttps://blog.csdn.net/Xin_101/article/details/122449693

本章讲解:HttpURLConnection,该类继承URLConnection。

2 接口

3 测试

3.1 Code

package com.monkey.java_study.web;

import com.google.gson.Gson;
import com.monkey.java_study.common.constant.BooleanConstant;
import com.monkey.java_study.common.constant.WebConstant;
import com.monkey.java_study.common.entity.PageEntity;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

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

/**
 * HttpUrlConnection请求接口测试样例.
 *
 * @author xindaqi
 * @date 2022-01-11 20:07
 */
public class HttpUrlConnectionTest {

    private static final Logger logger = LogManager.getLogger(HttpUrlConnectionTest.class);

    /**
     * GET请求.
     *
     * @param url 请求地址
     * @return 响应数据
     */
    public static String doGet(String url) {
        HttpURLConnection urlConnection = null;
        try {
            // 新建URL对象
            URL urlObject = new URL(url);
            // 打开URL连接
            urlConnection = (HttpURLConnection) urlObject.openConnection();
            // 设置请求方法
            urlConnection.setRequestMethod(WebConstant.GET_METHOD);
            // 设置请求头内容类型和字符集类型
            urlConnection.setRequestProperty(WebConstant.CONTENT_TYPE, WebConstant.APPLICATION_JSON);
            // 不使用缓存
            urlConnection.setUseCaches(BooleanConstant.FALSE);
            // 设置连接超时时间,单位:毫秒
            urlConnection.setConnectTimeout(2000);
            // 设置读取数据超时时间,单位:毫秒
            urlConnection.setReadTimeout(2000);

            // 获取响应
            return inputStreamProcess(urlConnection);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * POST请求.
     *
     * @param url    请求地址
     * @param params 请求参数:JSON字符串
     * @return 响应数据
     */
    public static String doPost(String url, String params) {
        HttpURLConnection urlConnection = null;
        try {
            // 新建URL对象
            URL urlObject = new URL(url);
            // 打开URL连接
            urlConnection = (HttpURLConnection) urlObject.openConnection();
            // 设置请求方法
            urlConnection.setRequestMethod(WebConstant.POST_METHOD);
            // 设置请求头内容类型和字符集类型
            urlConnection.setRequestProperty(WebConstant.CONTENT_TYPE, WebConstant.APPLICATION_JSON);
            urlConnection.setRequestProperty("accept", "*/*");
            urlConnection.setRequestProperty("connection", "Keep-Alive");
            urlConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 允许写出
            urlConnection.setDoOutput(BooleanConstant.TRUE);
            // 允许写入
            urlConnection.setDoInput(BooleanConstant.TRUE);
            // 不使用缓存
            urlConnection.setUseCaches(BooleanConstant.FALSE);
            // 设置连接超时时间,单位:毫秒
            urlConnection.setConnectTimeout(2000);
            // 设置读取数据超时时间,单位:毫秒
            urlConnection.setReadTimeout(2000);
            return responseProcess(urlConnection, params);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }

    }

    /**
     * 获取响应参数.
     *
     * @param urlConnection Http连接对象
     * @param params        请求参数
     * @return 响应数据
     */
    public static String responseProcess(URLConnection urlConnection, String params) {
        try (PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream())) {
            // 发送请求参数
            printWriter.print(params);
            // 刷新输出流
            printWriter.flush();
            return inputStreamProcess(urlConnection);
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    /**
     * 获取响应数据.
     *
     * @param urlConnection Http连接对象
     * @return 响应数据
     */
    public static String inputStreamProcess(URLConnection urlConnection) {
        try (InputStream inputStream = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                response.append(line);
            }
            return response.toString();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }

    public static void main(String[] args) {
        // GET:请求
        String getUrl = "http://localhost:9121/api/v1/mongodb/read?userId=0x001";
        String getResponse = doGet(getUrl);
        logger.info(">>>>>>>>>Get response:{}", getResponse);
        // POST:请求
        String postUrl = "http://localhost:9121/api/v1/mongodb/page";
        // 入参实体
        PageEntity pageEntity = new PageEntity(1, 2);
        Gson gson = new Gson();
        // 实体转JSON字符串
        String jsonString = gson.toJson(pageEntity);
        String postResponse = doPost(postUrl, jsonString);
        logger.info(">>>>>>>>>>Post response:{}", postResponse);
    }
}

3.2 测试结果

在这里插入图片描述

4 小结

  • HttpURLConnection发送POST请求:参数使用PrintWriter;
  • POST参数传入时转换为JSON字符串;
  • 可配置请求方法、连接超时时间、读取超时时间。
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
下面是使用 Java 代码编写 HttpURLConnection 发送 GET 和 POST 请求的示例: 1. 发送 GET 请求 ```java import java.net.*; import java.io.*; public class HttpGet { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 2. 发送 POST 请求 ```java import java.net.*; import java.io.*; public class HttpPost { public static void main(String[] args) { try { URL url = new URL("http://example.com"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setDoOutput(true); String input = "{\"username\":\"test\",\"password\":\"test\"}"; OutputStream os = conn.getOutputStream(); os.write(input.getBytes()); os.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 注意,在发送 POST 请求时需要设置 `Content-Type` 和向输出流中写入请求体。如果需要发送其他类型的请求,可以根据需要修改 `setRequestMethod` 和请求头部。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

天然玩家

坚持才能做到极致

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

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

打赏作者

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

抵扣说明:

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

余额充值