用 Java 傳送 HTTP 請求

Sheeraz Gul 2023年10月12日
  1. 在 Java 中使用 HttpURLConnection 傳送 HTTP 請求
  2. 在 Java 中使用 Apache HttpClient 來傳送 HTTP 請求
用 Java 傳送 HTTP 請求

我們可以使用 Java HttpURLConnection 和 Apache HttpClient 在 Java 中傳送 HTTP 請求。本教程將演示如何使用 Java 中的兩種方法傳送 HTTP 請求。

在 Java 中使用 HttpURLConnection 傳送 HTTP 請求

HttpURLConnection 是來自 Java.net 庫的內建方法。HTTP 請求有兩種型別,GET 和 POST。

讓我們嘗試使用 HttpURLConnection 傳送兩者。

在 Java 中使用 HttpURLConnection 傳送 GET HTTP 請求

讓我們嘗試使用 GET 方法 HttpURLConnection 方法來獲取我們網頁的內容。

例子:

package delftstack;

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

public class Get_HttpURLConnection {
  private static HttpURLConnection get_connection;

  public static void main(String[] args) throws IOException {
    String url = "https://www.delftstack.com/";

    try {
      // We retrieve the contents of our webpage.
      URL myurl = new URL(url);
      get_connection = (HttpURLConnection) myurl.openConnection();
      // Here we specify the connection type
      get_connection.setRequestMethod("GET");
      StringBuilder webpage_content;

      try (BufferedReader webpage =
               new BufferedReader(new InputStreamReader(get_connection.getInputStream()))) {
        String webpage_line;
        webpage_content = new StringBuilder();

        while ((webpage_line = webpage.readLine()) != null) {
          webpage_content.append(webpage_line);
          webpage_content.append(System.lineSeparator());
        }
      }

      System.out.println(webpage_content.toString());

    } finally {
      // Disconnect the connection
      get_connection.disconnect();
    }
  }
}

上面的程式碼會從 https://www.delftstack.com/ 輸出大量內容。

輸出:

獲取 HttpURL 連線

在 Java 中使用 HttpURLConnection 傳送 POST HTTP 請求

要使用 HttpURLConnection 通過 POST 方法傳送 HTTP 請求,我們必須設定請求屬性。下面的示例演示了通過 HttpURLConnection 和 POST 方法傳送 HTTP 請求,需要 URL 和 URL 引數。

package delftstack;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class POST_HttpURLConnection {
  private static HttpURLConnection post_connection;
  public static void main(String[] args) throws IOException {
    // URL
    String Post_URL = "https://httpbin.org/post";
    // URL Parameters
    String Post_URL_Parameters = "name=Michelle&occupation=Secretory";
    // Get Bytes of parameters
    byte[] Post_Data = Post_URL_Parameters.getBytes(StandardCharsets.UTF_8);
    try {
      URL Demo_URL = new URL(Post_URL);
      post_connection = (HttpURLConnection) Demo_URL.openConnection();
      post_connection.setDoOutput(true);
      // Set the method
      post_connection.setRequestMethod("POST");
      // The request property
      post_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
      // write the bytes or the data to the URL connection.
      try (DataOutputStream Data_Output_Stream =
               new DataOutputStream(post_connection.getOutputStream())) {
        Data_Output_Stream.write(Post_Data);
      }

      // Get the content
      StringBuilder Post_Webpage_Content;
      try (BufferedReader webpage =
               new BufferedReader(new InputStreamReader(post_connection.getInputStream()))) {
        String Webpage_line;
        Post_Webpage_Content = new StringBuilder();
        while ((Webpage_line = webpage.readLine()) != null) {
          Post_Webpage_Content.append(Webpage_line);
          Post_Webpage_Content.append(System.lineSeparator());
        }
      }
      System.out.println(Post_Webpage_Content.toString());

    } finally {
      post_connection.disconnect();
    }
  }
}

輸出:

{
    "args": {},
    "data": "",
    "files": {},
    "form": {
        "name": "Michelle",
        "occupation": "Secretory"
    },
    "headers": {
        "Accept": "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2",
        "Content-Length": "34",
        "Content-Type": "application/x-www-form-urlencoded",
        "Host": "httpbin.org",
        "User-Agent": "Java/17.0.2",
        "X-Amzn-Trace-Id": "Root=1-62308f8e-7aa124b15d6d3cd1114d6463"
    },
    "json": null,
    "origin": "182.182.126.98",
    "url": "https://httpbin.org/post"
}

在 Java 中使用 Apache HttpClient 來傳送 HTTP 請求

要首先使用 Apache HttpClient,你必須將庫新增到你的專案下載 Apache HttpClient 並將 jar 檔案新增到你的專案構建路徑庫中。

在 Java 中使用 Apache HttpClient 傳送 GET HTTP 請求

我們也可以使用 Apache HttpClient 並通過 GET 方法傳送 HTTP 請求來獲取內容。Apache HttpClient 比 HttpURLConnection 更容易。

例子:

package delftstack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class Get_HttpClient {
  public static void main(String[] args) throws IOException {
    try (CloseableHttpClient Apache_Get_Client = HttpClientBuilder.create().build()) {
      // Create a GET request
      HttpGet Apache_Get_Request = new HttpGet("https://www.delftstack.com/");
      // execute the request to get the response
      HttpResponse Apache_Get_Response = Apache_Get_Client.execute(Apache_Get_Request);
      // Get the content
      BufferedReader Webpage =
          new BufferedReader(new InputStreamReader(Apache_Get_Response.getEntity().getContent()));
      StringBuilder Webpage_Content = new StringBuilder();
      String Webpage_Content_Line;
      while ((Webpage_Content_Line = Webpage.readLine()) != null) {
        Webpage_Content.append(Webpage_Content_Line);
        Webpage_Content.append(System.lineSeparator());
      }
      System.out.println(Webpage_Content);
    }
  }
}

輸出:

Apache HttpClient

在 Java 中使用 Apache HttpClient 傳送 POST HTTP 請求

我們可以使用 Apache HttpClient 並通過 POST 方法傳送 HTTP 請求來獲取內容。

例子:

package delftstack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
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.HttpClientBuilder;

public class Post_HttpClient {
  public static void main(String[] args) throws IOException {
    try (CloseableHttpClient Apache_Post_Client = HttpClientBuilder.create().build()) {
      // Create a post request
      HttpPost Apache_Post_Request = new HttpPost("https://www.delftstack.com/");
      // pass parameters or set entity
      Apache_Post_Request.setEntity(new StringEntity("This is delftstack"));
      // execute the request to get the response
      HttpResponse Apache_Post_Response = Apache_Post_Client.execute(Apache_Post_Request);
      // Get the content
      BufferedReader Webpage =
          new BufferedReader(new InputStreamReader(Apache_Post_Response.getEntity().getContent()));
      StringBuilder Webpage_Content = new StringBuilder();
      String Webpage_line;
      while ((Webpage_line = Webpage.readLine()) != null) {
        Webpage_Content.append(Webpage_line);
        Webpage_Content.append(System.lineSeparator());
      }
      System.out.println(Webpage_Content);
    }
  }
}

輸出:

Apache HttpClient

Java 11 及之前的版本具有 HttpClient 的內建功能,新版本不支援該功能。HttpClient 與 Apache HTTPClient 不同。

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - Java HTTP