首页 > 编程语言 >Java发送HTTP GET/POST请求

Java发送HTTP GET/POST请求

时间:2024-05-07 10:33:39浏览次数:24  
标签:HTTP Java GET System new println import response out

一、Java 11 HttpClient

在Java11的java.net.http.*包中,有一个HttpClient类可以完成HTTP请求。
Java11HttpClientExample.java

package com.lyl.http;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class Java11HttpClientExample {
    private final HttpClient httpClient = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .build();

    public static void main(String[] args) throws Exception {
        Java11HttpClientExample obj = new Java11HttpClientExample();

        System.out.println("测试1:发送Http GET 请求");
        obj.sendGet();
        System.out.println("测试2:发送Http POST 请求");
        obj.sendPost();
    }

    private void sendGet() throws Exception {
        HttpRequest request = HttpRequest.newBuilder()
                .GET()
                .uri(URI.create("你请求数据的url地址"))
                .setHeader("User-Agent", "Java 11 HttpClient Bot")
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
        System.out.println(response.body());
    }

    private void sendPost() throws Exception {
        Map<Object, Object> data = new HashMap<>();
        data.put("username", "lyl");
        data.put("password", "123");

        HttpRequest request = HttpRequest.newBuilder()
                .POST(buildFormDataFromMap(data))
                .uri(URI.create("你请求数据的url地址"))
                .setHeader("User-Agent", "Java 11 HttpClient Bot")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode());
        System.out.println(response.body());

    }

    private static HttpRequest.BodyPublisher buildFormDataFromMap(Map<Object, Object> data) {
        var builder = new StringBuilder();
        for (Map.Entry<Object, Object> entry : data.entrySet()) {
            if (builder.length() > 0) {
                builder.append("&");
            }
            builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
            builder.append("=");
            builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
        }
        System.out.println(builder.toString());
        return HttpRequest.BodyPublishers.ofString(builder.toString());
    }
}

二、Java原生HttpURLConnection

本例使用HttpURLConnection(http)和HttpsURLConnection(https)
HttpURLConnectionExample.java

package com.lyl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionExample {
    private final String USER_AGENT = "Mozilla/5.0";
    public static void main(String[] args) throws Exception {
        HttpURLConnectionExample http = new HttpURLConnectionExample();
        System.out.println("测试1:发送Http GET 请求");
        http.sendGet();
        System.out.println("\n测试2:发送 Http POST 请求");
        http.sendPost();
    }

    // HTTP GET请求
    private void sendGet() throws Exception {
        String url = "你请求数据的url地址";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        //默认值GET
        con.setRequestMethod("GET");
        //添加请求头
        con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        System.out.println("\n发送 'GET' 请求到 URL : " + url);
        System.out.println("Response Code : " + responseCode);
        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());
    }

    // HTTP POST请求
    private void sendPost() throws Exception {
        String url = "你请求数据的url地址";
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        //添加请求头
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        //url传参的参数
        String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

        //发送Post请求
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\n发送 POST 请求到 URL : " + url);
        System.out.println("Post 参数 : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        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());
    }
}

三、Apache HttpClient

使用Apache HttpClient完成HTTP请求的发送需要添加Maven依赖,添加方式如下:
pom.xml

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.10</version>
</dependency>

HttpClientExample.java

package com.lyl.http;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HttpClientExample {
    private final CloseableHttpClient httpClient = HttpClients.createDefault();
    public static void main(String[] args) throws Exception {
        HttpClientExample obj = new HttpClientExample();
        try {
            System.out.println("测试1:发送Http GET 请求");
            obj.sendGet();

            System.out.println("测试2:发送Http POST 请求");
            obj.sendPost();
        } finally {
            obj.close();
        }
    }

    private void close() throws IOException {
        httpClient.close();
    }

    private void sendGet() throws Exception {
        HttpGet request = new HttpGet("你请求数据的url地址");
        request.addHeader("custom-key", "lyl");
        request.addHeader(HttpHeaders.USER_AGENT, "Googlebot");

        try (CloseableHttpResponse response = httpClient.execute(request)) {
            System.out.println(response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            Header headers = entity.getContentType();
            System.out.println(headers);
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                System.out.println(result);
            }
        }
    }

    private void sendPost() throws Exception {
		HttpPost post = new HttpPost("你请求数据的url地址");
		List<NameValuePair> urlParameters = new ArrayList<>();
		urlParameters.add(new BasicNameValuePair("username", "lyl"));
		urlParameters.add(new BasicNameValuePair("password", "123"));
		post.setEntity(new UrlEncodedFormEntity(urlParameters));

		try (CloseableHttpClient httpClient = HttpClients.createDefault();
			 CloseableHttpResponse response = httpClient.execute(post)) {
				System.out.println(EntityUtils.toString(response.getEntity()));
		}
    }
}

四、OkHttp

OkHttp在安卓上非常受欢迎,并广泛应用于许多网络项目中。
pom.xml

<dependency>
	<groupId>com.squareup.okhttp3</groupId>
	<artifactId>okhttp</artifactId>
	<version>4.2.2</version>
</dependency>

OkHttpExample.java

package com.lyl.http;

import okhttp3.*;
import java.io.IOException;

public class OkHttpExample {
    private final OkHttpClient httpClient = new OkHttpClient();
    public static void main(String[] args) throws Exception {
        OkHttpExample obj = new OkHttpExample();

        System.out.println("测试1:发送Http GET 请求");
        obj.sendGet();
        System.out.println("测试2:发送Http POST 请求");
        obj.sendPost();
    }

    private void sendGet() throws Exception {
        Request request = new Request.Builder()
                .url("你请求数据的url地址")
                .addHeader("custom-key", "lyl")  // add request headers
                .addHeader("User-Agent", "OkHttp Bot")
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            System.out.println(response.body().string());
        }
    }

    private void sendPost() throws Exception {
        RequestBody formBody = new FormBody.Builder()
                .add("username", "lyl")
                .add("password", "123")
                .build();

        Request request = new Request.Builder()
                .url("你请求数据的url地址")
                .addHeader("User-Agent", "OkHttp Bot")
                .post(formBody)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            System.out.println(response.body().string());
        }
    }
}

来源 https://blog.csdn.net/qq_43522889/article/details/127103358

标签:HTTP,Java,GET,System,new,println,import,response,out
From: https://www.cnblogs.com/hefeng2014/p/18176684

相关文章

  • 记一次java进程频繁挂掉问题排查修复
    前言最近业务部门有个java服务进程会突然无缘无故的挂掉,然后这个服务会产生一堆类似hs_err_pid19287.log这样的日志。业务部门负责人就把hs_err_pidxxx的日志发给我,让我帮忙看下问题。本文就来回顾一下,我是如何帮业务部门进行问题排查排查历程首先hs_err_pidxxx的日志有提示如......
  • 5.6为一个activity编写一个滚动界面的.java文件
    packagecom.example.yibaifen;importstaticandroidx.core.content.ContentProviderCompat.requireContext;importandroidx.annotation.NonNull;importandroidx.appcompat.app.AppCompatActivity;importandroidx.recyclerview.widget.DividerItemDecoration;importandro......
  • 排查Java反射调用的InvocationTargetExcetion问题
    在Java中通过反射调用方法时,常见的一个异常是:java.lang.reflect.InvocationTargetException,将异常信息打印到日志文件中时通常会有如下一句信息:java.lang.reflect.InvocationTargetException:null,由于在异常信息中存在"null",一开始就会非常敏感,会误以为是空指针异常。其实不然,从......
  • 什么是Java内存模型(JMM)?
    什么是Java内存模型(JMM)?一、JMM的相关概念Java内存模型简称JMM(JavaMemoryModel),是Java虚拟机所定义的一种抽象规范,用来屏蔽不同硬件和操作系统的内存访问差异,让java程序在各种平台下都能达到一致的内存访问效果。这里要注意两点:1)JMM是一个抽象的概念,并不是物理上的内存划分。2)J......
  • 如何使用 JavaScript 获取当前页面帧率 FPS
    可以通过计算每秒 window.requestAnimationFrame 的调用频率来做为FPS值。它接收一个回调函数,该回调函数会在浏览器下一次重绘之前执行。所以只要我们循环调用并记录单位时间内的调用次数就能计算当前页面的帧率了。效果展示在线预览-使用JavaScript获取当前页面帧率FP......
  • https加密机制
    参考:https://www.cnblogs.com/sxiszero/p/11133747.htmlhttps://www.cnblogs.com/technology178/p/14094375.html对称加密:只用一个秘钥的加解密,如果秘钥进行了泄漏,导致数据不安全非对称加密:非对称加密算法需要一组密钥对,分别是公钥和私钥,这两个密钥是成对出现的。公钥加密的内......
  • Unable to execute SonarScanner analysis: Fail to get bootstrap index from server
    1.背景编辑gitlab-ci流水线时,代码分析的job,maven使用sonar报错-mvncleanverifysonar:sonar-Dsonar.login=30c55d3b8d3d2569431fb39f3c488c90643a68442.错误信息[ERROR]Failedtoexecutegoalorg.sonarsource.scanner.maven:sonar-maven-plugin:3.11.0.3922:sonar(def......
  • Java中执行Shell命令
    Java中执行Shell命令Java执行Shell命令返回127引言在Java开发中,我们经常需要调用系统的Shell命令来完成一些特定的任务。然而,有时候执行Shell命令可能会返回一个特定的错误码,比如127。本文将介绍什么是Shell命令返回码,以及当Java执行Shell命令返回127时可能的原因和解决办法。......
  • Ubuntu 22.04.4 LTS 安装java
    记录一次Ubuntu22.04.4LTS安装java检查是否有自带安装jdkdpkg--list|grep-ijdk如果存在则卸载创建安装路径cd/usr/local/mkdirjavacdjava/解压java安装包tar-zxvf/home/to_install/jdk-8u281-linux-x64.tar.gz-C./解压完成后,/usr/local/java目录下......
  • ETL如何执行Java脚本
    ETLCloud提供了执行 Java 脚本的方式,让用户能够灵活地处理数据并实现各种复杂的数据处理任务。 ETLCloud在数据处理领域的应用优势主要体现在以下几个方面:灵活性:通过执行Java脚本,用户能够灵活定制数据处理逻辑,满足各种不同的业务需求。无论是简单的数据清洗还是复杂的数据......