在Java中调用HTTP接口,您可以使用以下几种方法:
使用Java内置的`HttpURLConnection`类
```java
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 = 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;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用Apache的`CloseableHttpClient`
```java
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;
public class CloseableHttpClientExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
System.out.println(response.getStatusLine());
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用Spring的`RestTemplate`
```java
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api";
String response = restTemplate.getForObject(url, String.class);
System.out.println(response);
}
}
使用OkHttp
```java
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://example.com/api")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.body().string());
} catch (Exception e) {
e.printStackTrace();
}
}
}