• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Java发送HTTP GET/POST请求

武飞扬头像
字符搬运工-蓝天
帮助1

在这篇文章中,将向你展示四种发送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

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

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgejief
系列文章
更多 icon
同类精品
更多 icon
继续加载