API调用错误示例:Java如何正确使用HTTP客户端
在Java中,我们可以使用各种HTTP客户端库来发送API请求。这里以java.net.HttpURLConnection
和流行的Apache HttpClient库为例。
- 使用HttpURLConnection:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpURLConnectionExample {
public static void main(String[] args) throws Exception {
// 创建URL对象
URL url = new URL("https://api.example.com/endpoint");
// 使用HttpURLConnection发送GET请求
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(1000); // 设置连接超时
int responseCode = connection.getResponseCode();
if (responseCode == 200) { // 如果响应码为200(成功),则读取响应内容
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
System.out.println("API Response Content: " + content.toString());
} else {
System.out.println("Failed to retrieve API data. Response Code: " + responseCode);
}
connection.disconnect();
}
}
- 使用Apache HttpClient库:
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientExample {
public static void main(String[] args) throws Exception {
// 创建CloseableHttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 使用Apache HttpClient发送GET请求
HttpGet httpGet = new HttpGet("https://api.example.com/endpoint");
HttpResponse response = httpClient.execute(httpGet);
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 200) {
String content = EntityUtils.toString(response.getEntity()));
System.out.println("API Response Content: " + content);
} else {
System.out.println("Failed to retrieve API data. Response Code: " + responseCode));
}
// 关闭HttpClient连接
httpClient.close();
}
}
请确保你已经添加了相应的依赖项。例如,如果你使用的是Apache HttpClient,你需要在项目的pom.xml文件中添加对应的依赖。
还没有评论,来说两句吧...