Java发送HTTP GET/POST请求

这篇具有很好参考价值的文章主要介绍了Java发送HTTP GET/POST请求。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

在这篇文章中,将向你展示四种发送Http的GET/POST的例子,如下:

一、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文章来源地址https://www.toymoban.com/news/detail-647056.html

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

到了这里,关于Java发送HTTP GET/POST请求的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【Java】Java发送httpPost,httpGet,httpPut,httpDelete请求

            业务场景:最近开发的项目使用的将文件图片和视频存储在Minio当中,但是准备上线申请资源的时候申请不到资源,就临时决定使用厂商提供的Api接口进行文件图片和视频上传,然后就需要在后端进行登录,文件校验和文件存储和文件检索等http请求的书写,所以下

    2024年02月07日
    浏览(27)
  • 使用C#发送HTTP的Get和Post请求

    2024年02月07日
    浏览(37)
  • (一)python发送HTTP 请求的两种方式(get和post )

    注:发送请求(包括请求行、方法类型、头、体) 常见的请求方式有get、post、put、delete            格式:requests.get() (内容: url必填; params选填:url参数字典) # ~ 无参数的get请求 # ~ 有参数的get请求 # ~ 使用params的get请求        知识扩展#  requests.post() post请求分为5种,常用

    2024年02月02日
    浏览(52)
  • tomcat(跟着宝哥学java:tomcat)tomcat安装 发布项目 配置eclipse http协议详解、get请求、post请求、url详解

    在%CATALINA_HOME%webapps下创建一个文件夹:hehe 在hehe中创建子文件夹:WEB-INF和资源文件夹(html/jsp/css/imgs/js) 在WEB-INF中创建子文件夹classes::存储java源文件生成的字节码文件 在WEB-INF中创建子文件夹lib::存储项目以来的jar 在WEB-INF中创建子web项目的核心配置文件:web.xml web

    2024年02月03日
    浏览(31)
  • C语言通过IXMLHTTPRequest以get或post方式发送http请求获取服务器文本或xml数据

    做过网页设计的人应该都知道ajax。 Ajax即Asynchronous Javascript And XML(异步的JavaScript和XML)。使用Ajax的最大优点,就是能在不更新整个页面的前提下维护数据。这使得Web应用程序更为迅捷地回应用户动作,并避免了在网络上发送那些没有改变的信息。 在IE浏览器中,Ajax技术就是

    2024年01月25日
    浏览(37)
  • Java发起Post 、Get 各种请求整合

    java发起get请求和post请求的各种情况整合。具体看代码以及注释。其中Constants.UTF8本质是指\\\"UTF-8\\\"

    2024年02月04日
    浏览(37)
  • java中使用hutool调用get请求,post请求

    一、hutool工具包实现 1、get请求 2、post请求 二、java net实现 1、java中http协议调用get请求 2、java中https协议调用get请求

    2024年02月11日
    浏览(31)
  • httpclient发送Get请求和Post请求

    1). 创建HttpClient对象,可以使用 HttpClients.createDefault() ; 2). 如果是无参数的GET请求,则直接使用构造方法 HttpGet(String url )创建HttpGet对象即可; 3)如果是带参数GET请求,则可以先使用 URIBuilder (String url)创建对象,再调用 addParameter (Stringparam, String value)`, 或setParameter(String param

    2024年02月06日
    浏览(42)
  • java封装https的get、post请求

    话不多说,直接进入正题。 原生的方法,java8中全部都有

    2024年02月11日
    浏览(31)
  • 使用Postman发送GET请求和POST请求

    Postman是一款流行的API测试和开发工具,它提供了一个易于使用的界面,用于发送HTTP请求并与REST、SOAP和其他Web服务进行交互。以下是对Postman的简单介绍: 发送HTTP请求:Postman允许您以简单直观的方式发送各种类型的HTTP请求(GET、POST、PUT、DELETE等)到指定的URL。您可以设置请

    2024年02月05日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包