在Java中,您可以使用java.net.HttpURLConnection或org.apache.http.client.HttpClient等类来进行HTTP请求。以下是使用HttpURLConnection类发送GET和POST请求的示例代码:
发送GET请求:
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class HttpGetRequestExample {
- public static void main(String[] args) {
- try {
- String url = "https://api.example.com/get-data";
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setRequestMethod("GET");
- int responseCode = connection.getResponseCode();
- if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- StringBuilder response = new StringBuilder();
- while ((line = reader.readLine()) != null) {
- response.append(line);
- }
- reader.close();
- System.out.println("Response: " + response.toString());
- } else {
- System.out.println("GET request failed. Response Code: " + responseCode);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
发送POST请求:
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class HttpPostRequestExample {
- public static void main(String[] args) {
- try {
- String url = "https://api.example.com/submit-data";
- String postData = "name=John&age=30"; // POST请求的数据
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setRequestMethod("POST");
- connection.setDoOutput(true);
- connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- OutputStream outputStream = connection.getOutputStream();
- outputStream.write(postData.getBytes());
- outputStream.flush();
- outputStream.close();
- int responseCode = connection.getResponseCode();
- if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功
- BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
- String line;
- StringBuilder response = new StringBuilder();
- while ((line = reader.readLine()) != null) {
- response.append(line);
- }
- reader.close();
- System.out.println("Response: " + response.toString());
- } else {
- System.out.println("POST request failed. Response Code: " + responseCode);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
在上述示例中,我们使用HttpURLConnection类来发送HTTP请求。对于GET请求,我们设置请求方法为"GET",并使用getInputStream()方法来获取响应数据。对于POST请求,我们除了设置请求方法为"OST"外,还设置了是否输出请求数据,并将POST数据写入输出流。然后,我们使用getInputStream()方法来获取响应数据。
"小礼物走一走,来肥宅自学平台支持我"
评论区
共条评论
- 这篇文章还没有收到评论,赶紧来抢沙发吧~
首页上页1下页尾页