Java基础系列:URLConnection请求POST和GET接口

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

本文讲解:URLConnection。

2 接口

2.1 Get接口

在这里插入图片描述

2.2 Post接口

在这里插入图片描述

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.URL;
import java.net.URLConnection;

/**
 * 我是描述信息.
 *
 * @author xindaqi
 * @date 2022-01-10 15:40
 */
public class UrlConnectionTest {

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

    /**
     * GET请求.
     *
     * @param url 请求地址
     * @return 响应数据
     */
    public static String doGet(String url) {
        URLConnection urlConnection = null;
        try {
            // 新建URL对象
            URL urlObject = new URL(url);
            // 打开URL连接
            urlConnection = urlObject.openConnection();
            // 设置请求头内容类型和字符集类型
            urlConnection.setRequestProperty(WebConstant.CONTENT_TYPE, WebConstant.APPLICATION_JSON);
            // 不使用缓存
            urlConnection.setUseCaches(BooleanConstant.FALSE);
            // 获取响应
            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) {
        URLConnection urlConnection = null;
        try {
            // 新建URL对象
            URL urlObject = new URL(url);
            // 打开URL连接
            urlConnection = urlObject.openConnection();
            // 设置请求头内容类型和字符集类型
            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);
            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 小结

  • URLConnection发送POST请求:参数使用PrintWriter;
  • POST参数传入时转换为JSON字符串。
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java中,可以使用HTTPClient或HttpURLConnection来发起GET请求。HTTPClient是一个第三方开源框架,对HTTP请求进行了很好的封装,而HttpURLConnectionJava的标准请求方式。下面是使用这两种方式发起GET请求的方法: 1. 使用HTTPClient: - 首先,需要导入HTTPClient的相关包,比如Apache的HttpClient 4.5.5。 - 创建HttpClient对象,并创建HttpGet请求对象,设置请求的URL。 - 执行请求,获取响应结果。 - 通过HttpResponse对象获取响应状态码、响应头和响应体等信息。 示例代码如下所示: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("http://example.com/api"); try { HttpResponse response = httpClient.execute(httpGet); // 处理响应结果 } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 使用HttpURLConnection: - 创建URL对象,设置请求的URL。 - 打开URLConnection连接,并设置请求方法为GET。 - 获取输入流,读取响应结果。 - 关闭连接。 示例代码如下所示: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuffer response = new StringBuffer(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理响应结果 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上是使用Java发起GET请求的两种实现方法,可以根据具体需求选择适合的方式进行开发。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [java发起http请求获取返回的Json对象方法](https://download.csdn.net/download/weixin_38747025/12957986)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [JAVA发送GET和POST请求](https://blog.csdn.net/sunyanchun/article/details/128392329)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

天然玩家

坚持才能做到极致

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

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

打赏作者

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

抵扣说明:

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

余额充值