在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 = 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();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 使用第三方库,如Apache HttpClient:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://example.com/api");
try {
HttpResponse response = httpClient.execute(httpGet);
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. 使用Spring框架的`RestTemplate`:
import org.springframework.web.client.RestTemplate;
public class RestClientExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com/api";
String result = restTemplate.getForObject(url, String.class);
System.out.println(result);
}
}
4. 使用Java 8及以上版本的流API和`HttpClient`:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Java11HttpClientExample {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://example.com/api"))
.GET()
.build();
try {
HttpResponse
response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上示例展示了如何使用不同的方法调用HTTP接口。您可以根据项目需求选择合适的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/146098.html