Java 发送 HTTP 请求的两种常用方法

本文主要介绍在 Java 编程中发送 HTTP 请求的两种常用方法:

  • JDK 原生的 HttpURLConnection 发送 HTTP 请求
  • Apache HhttpClient 发送 HTTP 请求

两种方法都可以发送 HTTP 请求,第一种是 Java 原生的,因此使用起来相对麻烦一些,第二种是通过第三方的包来实现,这个包是 Apache 旗下的专门用来发送 HTTP 请求的 HttpClient 包,是对 Java 原生的 HttpURLConnection 扩展,因此功能也更加强大,使用起来也相对简单一些,目前这种方式发送 HTTP 请求应用比较广泛,因此主要学习这种方式。

Apache HttpClient 官方文档见这里:http://hc.apache.org/httpcomponents-client-5.1.x/

Talk is cheap. Show me the code. 下面看具体使用代码示例。

1、JDK 原生的 HttpURLConnection 发送 HTTP 请求 GET/POST

基于 JDK 原生的 HttpURLConnection 类,简单封装了下 HTTP GET 和 POST 请求方法,重在学习使用。

package com.example.demo.common.utils;
/**
 * Created by qianghaohao on 2021/5/16
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @description: 使用 java 原生 HttpURLConnection 类发送 http 请求
 * @author: qianghaohao
 * @time: 2021/5/16
 */
public class HttpURLConnectionUtils {
   
    public static String doGet(String httpUrl) {
   
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        String result = null;
        try {
   
            // 创建远程url连接对象
            URL url = new URL(httpUrl);

            // 通过远程url连接对象打开一个连接,强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();

            // 设置连接方式:get
            connection.setRequestMethod("GET");

            // 设置连接主机服务器的超时时间:15000毫秒
            connection.setConnectTimeout(15000);

            // 设置读取远程返回的数据时间:60000毫秒
            connection.setReadTimeout(60000);

            // 通过connection连接,获取输入流
            if (connection.getResponseCode() == 200) {
   
                inputStream = connection.getInputStream();
                // 封装输入流is,并指定字符集
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                // 存放数据
                StringBuilder sb = new StringBuilder();
                String temp;
                while ((temp = bufferedReader.readLine()) != null) {
   
                    sb.append(temp);
                    sb.append(System.lineSeparator());  // 这里需要追加换行符,默认读取的流没有换行符,需要加上才能符合预期
                }
                result = sb.toString();
            }
        } catch (IOException e) {
   
            e.printStackTrace();
        } finally {
   
            // 关闭资源
            if (null != bufferedReader) {
   
                try {
   
                    bufferedReader.close();
                } catch (IOException e) 
  • 2
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java使用HTTP请求方法有多种,其中比较常用的是使用HttpURLConnection类或Apache HttpClient库。以下是使用HttpURLConnection类的示例代码: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; public class HttpUrlConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api"); // 替换为你要请求的URL HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); // 设置请求方法为POST,也可以是GET等 con.setRequestProperty("Content-Type", "application/json"); // 设置请求头 con.setDoOutput(true); // 允许写请求体 // 构造请求体 String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; OutputStream os = con.getOutputStream(); os.write(requestBody.getBytes()); os.flush(); os.close(); // 发送请求 int responseCode = con.getResponseCode(); // 读取响应 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 输出响应 System.out.println(response.toString()); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } } ``` 使用Apache HttpClient库的示例代码: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) { try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("http://example.com/api"); // 替换为你要请求的URL httpPost.setHeader("Content-Type", "application/json"); // 设置请求头 // 构造请求体 String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; StringEntity entity = new StringEntity(requestBody); httpPost.setEntity(entity); // 发送请求 CloseableHttpResponse response = httpclient.execute(httpPost); // 读取响应 HttpEntity responseEntity = response.getEntity(); String responseString = EntityUtils.toString(responseEntity); // 输出响应 System.out.println(responseString); // 关闭连接 response.close(); httpclient.close(); } catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } } ``` 以上两种方法都可以用于HTTP请求,其中HttpURLConnection类是Java自带的,而Apache HttpClient库需要自行导入。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值