在Java语言中,调用第三方接口通常涉及使用HTTP客户端库来发送HTTP请求并接收响应。以下是几种常用的方式,包括它们的pom依赖、代码示例和适用场景:
1. 使用HttpURLConnection
pom依赖:无需额外依赖,因为HttpURLConnection
是Java标准库的一部分。
代码示例:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印结果
System.out.println(response.toString());
} else {
System.out.println("GET request not worked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
适用场景:适用于简单的HTTP请求,不需要复杂的客户端配置或功能。
2. 使用Apache HttpClient
pom依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
代码示例:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientExample {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet request = new HttpGet("https://api.example.com/data");
try (CloseableHttpResponse response = httpClient.execute(request)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println(result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
适用场景:适用于需要更高级功能(如自定义请求头、处理重定向、使用连接池等)的HTTP客户端。
3. 使用OkHttp
pom依赖(注意:OkHttp通常通过Gradle或Maven的JCenter仓库获取,但JCenter已关闭,因此你可能需要切换到其他仓库或使用其他方式获取依赖):
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
代码示例:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class OkHttpExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// 显示响应体
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
适用场景:适用于需要异步请求、拦截器、连接池等高级功能的HTTP客户端。OkHttp以其简洁的API和强大的功能而著称。
4. 使用Spring RestTemplate
pom依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
代码示例:
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class RestTemplateExample implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(RestTemplateExample.class, args);
}
@Override
public void run(String... args) throws Exception {
RestTemplate restTemplate = new RestTemplate();
String url = "https://api.example.com/data";
String response = restTemplate.getForObject(url, String.class);
System.out.println(response);
}
}
适用场景:适用于Spring Boot应用中的HTTP请求。RestTemplate提供了丰富的RESTful服务访问功能,与Spring框架紧密集成。
总结
HttpURLConnection
:适用于简单的HTTP请求,无需额外依赖。- Apache HttpClient:适用于需要更高级功能的HTTP客户端。
- OkHttp:适用于需要异步请求、拦截器、连接池等高级功能的HTTP客户端,API简洁。
- Spring RestTemplate:适用于Spring Boot应用中的HTTP请求,与Spring框架紧密集成。
选择哪种方式取决于你的具体需求和项目背景。