在Java中使用6种方法进行http请求

Java 中发出 HTTP 请求的常见方法有:

  1. Java SE 的 HttpURLConnection 类
  2. Apache 的 HttpClient 第三方库
  3. Spring 的 RestTemplate 类
  4. JavaFX 的 WebEngine 类
  5. OkHttp 第三方库
  6. Retrofit 第三方库

以上列举的方法都是可以用来发出 HTTP 请求的,具体的使用方法参考如下
也可以参考官方文档和代码示例。

  1. Java SE 的 HttpURLConnection 类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

import java.io.*;
import java.net.*;

public class HttpRequestExample {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
int status = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
con.disconnect();
System.out.println(content);
}
}
  1. Apache 的 HttpClient 第三方库:
1
2
3
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet("http://www.example.com");
CloseableHttpResponse response = client.execute(request);
  1. Spring 的 RestTemplate 类:
1
2
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://www.example.com", String.class);
  1. JavaFX 的 WebEngine 类:
1
2
WebEngine engine = new WebEngine();
engine.load("http://www.example.com");
  1. OkHttp 第三方库:
1
2
3
4
5
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.example.com")
.build();
Response response = client.newCall(request).execute();
  1. Retrofit 第三方库:
1
2
3
4
5
6
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.example.com")
.build();
MyApi api = retrofit.create(MyApi.class);
Call<ResponseBody> call = api.getData();
Response<ResponseBody> response = call.execute();

以上是常见的 Java 中发出 HTTP 请求的方法以及具体的示例,实际应用中可以根据需要选择适合的方法。