共计 2106 个字符,预计需要花费 6 分钟才能阅读完成。
Java 可以通过以下几种方式调用第三方 HTTP 接口:
- 使用 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();
}
}
}
- 使用第三方库 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();
}
}
}
- 使用第三方库 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 接口的方式,根据具体情况选择合适的方式。
丸趣 TV 网 – 提供最优质的资源集合!
正文完
发表至: Java
2023-12-21