温馨提示×

Java怎么调用第三方http接口

小亿
121
2023-08-17 10:17:13
栏目: 编程语言

Java可以通过以下几种方式调用第三方HTTP接口:

  1. 使用Java内置的HttpURLConnection类:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpClient {
public static void main(String[] args) {
try {
// 创建URL对象
URL url = new URL("http://example.com/api");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 发送请求
int statusCode = connection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_OK) {
// 读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应
System.out.println(response.toString());
} else {
System.out.println("请求失败,状态码:" + statusCode);
}
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
  1. 使用第三方库Apache HttpClient:
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClient {
public static void main(String[] args) {
try {
// 创建HttpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建HttpGet对象
HttpGet httpGet = new HttpGet("http://example.com/api");
// 发送请求并获取响应
HttpResponse response = httpClient.execute(httpGet);
// 获取响应实体
HttpEntity entity = response.getEntity();
// 解析实体中的内容
String result = EntityUtils.toString(entity);
// 处理响应
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
  1. 使用第三方库OkHttp:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpClient {
public static void main(String[] args) {
try {
// 创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
// 创建Request对象
Request request = new Request.Builder()
.url("http://example.com/api")
.build();
// 发送请求并获取响应
Response response = client.newCall(request).execute();
// 获取响应体的内容
String result = response.body().string();
// 处理响应
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}

以上是三种常见的Java调用第三方HTTP接口的方式,根据具体情况选择合适的方式。

0