Java调用http接口的几种方式(HttpURLConnection、OKHttp、HttpClient、RestTemplate)
Java调用HTTP接口可以使用以下几种方式:
HttpURLConnection
:Java内置的轻量级HTTP客户端。OKHttp
:一个高效的HTTP客户端,支持连接池、缓存等机制。HttpClient
:Apache的HTTP客户端,功能丰富,但不是Android标准库的一部分。RestTemplate
:Spring框架中用于访问REST服务的客户端。
以下是每种方式的简单示例代码:
HttpURLConnection
URL url = new URL("http://example.com/api");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 处理response.toString()
}
conn.disconnect();
OKHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://example.com/api")
.get()
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String responseBody = response.body().string();
// 处理responseBody
}
HttpClient
(需要Apache HttpClient库)
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://example.com/api");
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
String responseBody = EntityUtils.toString(response.getEntity());
// 处理responseBody
}
RestTemplate
(Spring框架)
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://example.com/api", String.class);
// 处理response
评论已关闭