使用Java API发送HTTP请求示例
在Java中,你可以使用多种方式来发送HTTP请求。以下是使用Java标准库中的HttpURLConnection
类来发送一个简单的GET请求的示例代码:
```javaimport java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetRequestExample {
public static void main(String[] args) {
String urlString = “http://example.com“; //替换为你想要请求的URL try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法,默认是GET 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;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//打印结果 System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}``这个示例展示了如何创建一个GET请求,设置请求头,并读取响应。如果你需要发送POST请求或者需要处理更复杂的HTTP特性(如HTTPS、连接池等),你可能需要使用更高级的库,比如Apache HttpClient或者Java11中引入的
HttpClient`。
以下是使用Java11的HttpClient
发送GET请求的示例:
```javaimport java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientExample {
public static void main(String[] args) {
String urlString = “http://example.com“; //替换为你想要请求的URL HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(urlString))
.header(“Accept”, “application/json”)
.build();
try {
HttpResponse
System.out.println(“Response Code: “ + response.statusCode());
System.out.println(“Response Body: “ + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}``这个示例使用了Java11中引入的
HttpClient,它提供了一个更现代和更强大的API来处理HTTP请求。记得在实际使用时替换
urlString`为你想要请求的实际URL。
还没有评论,来说两句吧...