如何构造HTTP请求

直接通过浏览器地址栏

具体的流程,直接通过浏览器地址栏,输入一个url =>构造出一个GET请求

html中,一些特殊标签,也会触发GET请求

1) link
2) script
3) img
4) a

以上的几个标签都会触发Get请求了.

form表单,可以触发GET和POST请求

form 的重要参数:
action: 构造的 HTTP 请求的 URL 是什么.
method: 构造的 HTTP 请求的 方法 是 GET 还是 POST (form 只支持 GET 和 POST).
input 的重要参数:
type: 表示输入框的类型. text 表示文本, password 表示密码, submit 表示提交按钮.
name: 表示构造出的 HTTP 请求的 query string 的 key. query string 的 value 就是输入框的用户
输入的内容.
value: input 标签的值. 对于 type 为 submit 类型来说, value 就对应了按钮上显示的文本.

<form action="http://abcdef.com/myPath" method="GET">
    <input type="text" name="userId">
    <input type="text" name="classId">
    <input type="submit" value="提交">
</form>

如果是post请求,就改为method方法改为post就可以了.

<form action="http://abcdef.com/myPath" method="POST">
    <input type="text" name="userId">
    <input type="text" name="classId">
    <input type="submit" value="提交">
</form>

通过 ajax 构造 HTTP 请求

从前端角度, 除了浏览器地址栏能构造 GET 请求, form 表单能构造 GET 和 POST 之外, 还可以通过 ajax 的方式来构造 HTTP 请求. 并且功能更强大.
ajax 全称 Asynchronous Javascript And XML, 是 2005 年提出的一种 JavaScript 给服务器发送.

HTTP 请求的方式.
特点是可以不需要 刷新页面/页面跳转 就能进行数据传输.
在 JavaScript 中可以通过 ajax 的方式构造 HTTP 请求.

<!DOCTYPE html>
<html>
<head>
  <title>简历填写</title>
</head>
<body>
  <h1>简历填写</h1>

  <form id="resumeForm">
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name" required><br>

    <label for="email">邮箱:</label>
    <input type="email" id="email" name="email" required><br>

    <label for="phone">电话:</label>
    <input type="tel" id="phone" name="phone" required><br>

    <label for="education">教育背景:</label>
    <textarea id="education" name="education" required></textarea><br>

    <button type="submit">提交</button>
  </form>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    $(document).ready(function() {
      // 监听表单的提交事件
      $('#resumeForm').submit(function(event) {
        event.preventDefault(); // 阻止表单默认的提交行为

        // 使用Ajax发送表单数据
        $.ajax({
          url: 'https://api.example.com/resume',
          method: 'POST',
          data: $(this).serialize(), // 序列化表单数据
          success: function(response) {
            console.log('提交成功');
            console.log(response);
            // 处理提交成功的逻辑
          },
          error: function(xhr, status, error) {
            console.log('提交失败');
            console.log('Error:', error);
            // 处理提交失败的逻辑
          }
        });
      });
    });
  </script>
</body>
</html>

在这里插入图片描述

以下是一个简单的HTML代码示例,用于填写简历信息:

html
Copy code

简历填写

简历填写


<label for="email">邮箱:</label>
<input type="email" id="email" name="email" required><br>

<label for="phone">电话:</label>
<input type="tel" id="phone" name="phone" required><br>

<label for="education">教育背景:</label>
<textarea id="education" name="education" required></textarea><br>

<button type="submit">提交</button>
在这个例子中,我们创建了一个简单的HTML表单,包含了姓名、邮箱、电话和教育背景等字段。用户填写完表单后,点击提交按钮,通过Ajax发送POST请求将表单数据发送到指定的API端点(示例中为https://api.example.com/resume)。

我们使用jQuery库来简化Ajax请求的处理。在脚本部分,我们首先监听表单的提交事件,当表单提交时,阻止默认的提交行为,并使用 . a j a x ( ) 方法发送 P O S T 请求。请求的 U R L 、方法和数据通过配置选项指定,其中 d a t a 选项使用 .ajax()方法发送POST请求。请求的URL、方法和数据通过配置选项指定,其中data选项使用 .ajax()方法发送POST请求。请求的URL、方法和数据通过配置选项指定,其中data选项使用(this).serialize()将表单数据序列化。

在请求成功或失败时,我们分别执行相应的回调函数,将返回的响应或错误信息打印到控制台。您可以根据实际需求,自行编写处理成功和失败情况的逻辑。

通过 Java socket 构造 HTTP 请求

所谓的 “发送 HTTP 请求”, 本质上就是按照 HTTP 的格式往 TCP Socket 中写入一个字符串.
所谓的 “接受 HTTP 响应”, 本质上就是从 TCP Socket 中读取一个字符串, 再按照 HTTP 的格式来解析.
我们基于 Socket 的知识, 完全可以构造出一个简单的 HTTP 客户端程序, 用来发送各种类型的 HTTP 请求.

public class HttpClient {
    private Socket socket;
    private String ip;
    private int port;
    public HttpClient(String ip, int port) throws IOException {
        this.ip = ip;
        this.port = port;
        socket = new Socket(ip, port);
   }
    public String get(String url) throws IOException {
        StringBuilder request = new StringBuilder();
        // 构造首行
        request.append("GET " + url + " HTTP/1.1\n");
        // 构造 header
        request.append("Host: " + ip + ":" + port + "\n");
        // 构造 空行
        request.append("\n");
        // 发送数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
        // 读取响应数据
        InputStream inputStream = socket.getInputStream();
        byte[] buffer = new byte[1024 * 1024];
        int n = inputStream.read(buffer);
        return new String(buffer, 0, n, "utf-8");
   }
    public String post(String url, String body) throws IOException {
        StringBuilder request = new StringBuilder();
        // 构造首行
        request.append("POST " + url + " HTTP/1.1\n");
        // 构造 header
        request.append("Host: " + ip + ":" + port + "\n");
        request.append("Content-Length: " + body.getBytes().length + "\n");
        request.append("Content-Type: text/plain\n");
        // 构造 空行
        request.append("\n");
        // 构造 body
        request.append(body);
        // 发送数据
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(request.toString().getBytes());
        // 读取响应数据
        InputStream inputStream = socket.getInputStream();
        byte[] buffer = new byte[1024 * 1024];
        int n = inputStream.read(buffer);
        return new String(buffer, 0, n, "utf-8");
   }
    public static void main(String[] args) throws IOException {
        HttpClient httpClient = new HttpClient("42.192.83.143", 8080);
        String getResp = httpClient.get("/AjaxMockServer/info");
        System.out.println(getResp);
        String postResp = httpClient.post("/AjaxMockServer/info", "this is 
body");
        System.out.println(postResp);
   }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

忘忧记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值