java发送http请求的多种方式

原生java发送http请求

package com.cyz;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * @author cyz
 * @since 2023/11/8 9:50
 */
public class CustHttp {
    public static String post(String targetUrl, String params) throws IOException {
        URL url = new URL(targetUrl);
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            URLConnection urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Request-Origion", "SwaggerBootstrapUi");
            urlConnection.setRequestProperty("accept", "*/*");
            urlConnection.setRequestProperty("Content-Type", "application/json");

            //post请求要使用下面两个
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);

            out = new PrintWriter(urlConnection.getOutputStream());
            out.write(params);
            out.flush();
            in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            String res = "";
            String line = "";
            while ((line = in.readLine()) != null) {
                res += line;
            }
            return res;
        } finally {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        }
    }

    public static String get(String targetUrl, String token) throws IOException {
        URL url = new URL(targetUrl);
        BufferedReader in = null;
        try {
            URLConnection connection = url.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.setRequestProperty("Authorization", token);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));

            String res = "";
            String line = "";
            while ((line = in.readLine()) != null) {
                res += line;
            }
            return res;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        String post = post("http://10.21.1.154:19500/api/v1/user/login", "{\n" +
                "\t\"captcha\": \"1\",\n" +
                "\t\"code\": \"1\",\n" +
                "\t\"password\": \"123456\",\n" +
                "\t\"username\": \"superAdmin\"\n" +
                "}");
        System.out.println(post);

        String s = get("http://10.21.1.154:19500/api/v1/user/getBaseInfo?opId=1808",
                "/bv1CXBJczpJm6d46e+KkT2qNC00Bd9L/b9Y4Awq5P3dEaQySoJP1uCOG3uP9ubydsBSCeD/UsUoz" +
                        "7ZHTOMeNCQtEuEYeu82NV4QahqWJ8zcDgPpC5ev+wII7ApYK/z54mrfvKW2/A4ferRB4EJXuwfzoRfm3RRh" +
                        "THTiMnRuLY1BqUZP+3rCpcinWpeCpZVGEPnImU4ZDmUNtOG4pn0Dexk3UMp838a+sgkXcRJKLCcvQd0i2Jez7MiJ" +
                        "iQrGedZVN6XXiPViETRV7NQNhBQCqZO4C9P+c9/tBuY2Qq6WrZhNhxJvphYiaIuG+zyjL+ZkYQgeKeVo6waecCnnLoBZV2" +
                        "nPmbbAmiqCrmNfueJG3wv/lBvVyKg+C1n1rjKnTIxkmVbC8v44TwBY3gi6HaBf4IFxf/hoiBgv1WqJZfPf4GpL6f2e0nhN" +
                        "s4ho5M6jQTmmjAKOei8P3FtaIogvsc9HPg==");
        System.out.println(s);
    }
}

使用Hutool工具类

依赖

       <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.18</version>
        </dependency>

HttpRequest

 HttpResponse getBaidu = HttpRequest.get("www.baidu.com")
                .execute();
        System.out.println(getBaidu.body());

        HttpResponse execute = HttpRequest.post("http://10.21.1.154:19500/api/v1/user/login")
                .header("Request-Origion", "SwaggerBootstrapUi")
                .header("accept", "*/*")
                .header("Content-Type", "application/json")
                .body("{\n" +
                        "\t\"captcha\": \"1\",\n" +
                        "\t\"code\": \"1\",\n" +
                        "\t\"password\": \"123456\",\n" +
                        "\t\"username\": \"superAdmin\"\n" +
                        "}").execute();
        System.out.println(execute.body());

HttpUtil

  String s = HttpUtil.get("www.baidu.com");
        System.out.println(s);

HttpResponse execute = HttpUtil.createPost("http://10.21.1.154:19500/api/v1/user/login")
                .header("Request-Origion", "SwaggerBootstrapUi")
                .header("accept", "*/*")
                .header("Content-Type", "application/json")
                .body("{\n" +
                        "\t\"captcha\": \"1\",\n" +
                        "\t\"code\": \"1\",\n" +
                        "\t\"password\": \"123456\",\n" +
                        "\t\"username\": \"superAdmin\"\n" +
                        "}").execute();
        System.out.println(execute.body());

resttemplate

(省略)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java发送HTTP请求可以使用多种方式,其中最常见的方式是使用Java的内置类库`java.net`或第三方库如Apache HttpClient。 使用`java.net`类库发送HTTP请求的示例如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpRequestExample { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://example.com"); // 打开连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法 connection.setRequestMethod("GET"); // 发送请求 int responseCode = connection.getResponseCode(); // 读取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 输出响应结果 System.out.println("Response Code: " + responseCode); System.out.println("Response Body: " + response.toString()); // 关闭连接 connection.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } ``` 上述代码使用`HttpURLConnection`类发送GET请求,并输出响应结果。 另外,使用第三方库Apache HttpClient发送HTTP请求也非常常见。你可以通过添加Maven或Gradle依赖来使用Apache HttpClient。以下是一个使用Apache HttpClient发送GET请求的示例: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpRequestExample { public static void main(String[] args) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // 创建HttpGet对象 HttpGet httpGet = new HttpGet("http://example.com"); // 发送请求 CloseableHttpResponse response = httpClient.execute(httpGet); // 读取响应 String responseBody = EntityUtils.toString(response.getEntity()); // 输出响应结果 System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); System.out.println("Response Body: " + responseBody); // 关闭响应 response.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这是一个使用Apache HttpClient发送GET请求的简单示例,它与`java.net`示例相似,但使用了不同的类和方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值