在Java中,调用HTTP接口有多种方式,各种方法适用于不同的场景。本文将介绍四种常用的HTTP请求方式:HttpURLConnection、OKHttp、HttpClient和RestTemplate,并提供相应的代码示例。
1. 使用 HttpURLConnection
HttpURLConnection
是Java内置的HTTP客户端,它是较为底层的API,使用起来需要处理相对较多的细节。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) {
String urlString = "http://www.example.com/api";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response Content: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 使用 OKHttp
OKHttp
是一个流行的第三方HTTP客户端,提供了更简洁的API和更强大的功能。
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();
String url = "http://www.example.com/api";
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
if (response.isSuccessful()) {
System.out.println("Response Code: " + response.code());
System.out.println("Response Body: " + response.body().string());
} else {
System.out.println("Request Failed: " + response.code());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. 使用 HttpClient
HttpClient
是Apache提供的HTTP客户端,支持各种HTTP协议,适用于复杂的网络请求。
import org.apache.http.HttpResponse;
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 HttpClientExample {
public static void main(String[] args) {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet request = new HttpGet("http://www.example.com/api");
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + statusCode);
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Response Body: " + responseBody);
} catch (IOException e) {
e.printStackTrace();
}
}
}
4. 使用 RestTemplate
RestTemplate
是Spring框架提供的一个高层次REST客户端,适合在Spring应用中使用。
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://www.example.com/api";
String response = restTemplate.getForObject(url, String.class);
System.out.println("Response Body: " + response);
}
}
总结
以上四种方法均可用于发送HTTP请求,并根据需求选择合适的方式:
HttpURLConnection
适用于较简单的HTTP请求,且不引入外部依赖。OKHttp
提供了更友好的API和更多配置选项,适合需要处理较复杂请求的项目。HttpClient
这是一个功能比较强大的客户端,适合处理多种HTTP协议的请求。RestTemplate
适合Spring应用,支持多种RESTful操作,使用简单。
选择合适的HTTP客户端,可以大大提高开发效率和代码的可维护性。