如何使用Java进行HTTP请求:GET/POST示例

原创 灰太狼 2024-09-29 14:45 95阅读 0赞

在Java中,我们可以使用java.net.HttpURLConnection或者更高级的库如OkHttp来执行HTTP请求。

以下是一个使用HttpURLConnection进行GET和POST请求的示例:

  1. GET请求示例:
    ```java
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;

public class GetExample {
public static void main(String[] args) {
String urlStr = “http://example.com“; // 你要访问的URL
try {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

  1. // 设置请求方法为GET
  2. connection.setRequestMethod("GET");
  3. // 检查连接状态,如果成功则返回响应码
  4. int responseCode = connection.getResponseCode();
  5. System.out.println("Response Code: " + responseCode);
  6. // 读取响应内容(以字符串形式)
  7. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
  8. String inputLine;
  9. StringBuilder contentSoFar = new StringBuilder();
  10. while ((inputLine = in.readLine()) != null)) {
  11. contentSoFar.append(inputLine);
  12. }
  13. System.out.println("Response Content: " + contentSoFar.toString());
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }

}

  1. 2. POST请求示例:
  2. ```java
  3. import java.io.BufferedReader;
  4. import java.io.InputStreamReader;
  5. import java.net.HttpURLConnection;
  6. import java.net.URL;
  7. public class PostExample {
  8. public static void main(String[] args) {
  9. String urlStr = "http://example.com/api"; // 你要访问的URL
  10. String postData = "{\"key1\":\"value1\", \"key2\":\"value2\"}"; // 要发送的数据
  11. try {
  12. URL url = new URL(urlStr);
  13. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  14. // 设置请求方法为POST
  15. connection.setRequestMethod("POST");
  16. // 选择Post数据的类型(这里我们使用application/json)
  17. connection.setDoOutput(true);
  18. // 将要发送的数据写入到输出流中
  19. byte[] bytes = postData.getBytes();
  20. OutputStream outputStream = connection.getOutputStream();
  21. outputStream.write(bytes);
  22. // 检查连接状态,如果成功则返回响应码
  23. int responseCode = connection.getResponseCode();
  24. System.out.println("Response Code: " + responseCode);
  25. BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))));
  26. String inputLine;
  27. StringBuilder contentSoFar = new StringBuilder();
  28. while ((inputLine = in.readLine()) != null)) {
  29. contentSoFar.append(inputLine);
  30. }
  31. System.out.println("Response Content: " + contentSoFar.toString());
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34. }
  35. }
  36. }

以上就是使用Java进行HTTP GET和POST请求的基本示例。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,95人围观)

还没有评论,来说两句吧...

相关阅读