给你三种不同的方法实现GET和POST请求


前言

        又是一个新的开始了。过完开心的假期,又开始投入到了紧张又刺激的学习时间。小编给你们总结了一下小编学习到的三种发送请求的方法。感兴趣的小伙伴快来一起看看吧!快学起来学起来!!!!!


 

1、jQuery中的Ajax

首先在开始讲解知识点之前,我们需要先知道什么是Ajax? 

那么什么是Ajax呢?

Ajax的全称是Asynchronous JavaScript And XML (异步JavaScript 和XML)

简单理解:在网页中利用XMLHttpRequest对象服务器进行数据交互,就是Ajax

简单介绍了一些什么是Ajax之后那我们就开始今天的分享吧!

1.1、$.get()

$.get()语法结构:$.get(url,[data],[callback])

属性介绍

  • url:string(字符型)必选,要请求的资源地址
  • data:object对象,可选可不选,请求资源期间携带的参数
  • callback:function函数,可选可不选,请求成功时的回调函数

 $.get()发起不带参数的GET请求:

首先要引用我们的jquery.js文件

<script src="jquery.js"></script>
<body>
    <button id="btnGET">发起不带参数的get请求</button>
    <script>
        $(function() {
            $('#btnGET').on('click', function() {
                $.get('http://www.liulongbin.top:3006/api/getbooks', function(res) {
                    console.log(res);
                })
            })
        })
    </script>
</body>

$.get()发起带参数的GET请求:

<body>
    <button id="btnINfo">发起带参数的get请求</button>
    <script>
        $(function() {
            $('#btnINfo').on('click', function() {
                $.get('http://www.liulongbin.top:3006/api/getbooks', {
                    id: 1
                }, function(res) {
                    console.log(res);
                })
            })
        })
    </script>
</body>

1.2、$.post() 

$.post()语法格式:$.post(url,[data],[callback]) 

$.post()发起POST请求: 

<body>
    <button id="postBtn">发起POST请求</button>
    <script>
        $(function() {
            $('#postBtn').on('click', function() {
                $.post('http://www.liulongbin.top:3006/api/addbook', {
                    bookname: '水浒传',
                    author: '施耐庵',
                    publisher: '天津图书出版社'
                }, function(res) {
                    console.log(res);
                })
            })
        })
    </script>
</body>

1.3、$.ajax() 

$.ajax()语法格式 :

$.ajax({
    type:'',//请求的方式,如get或者post
    url:'',//请求的URL地址
    data:{},//这次请求要携带的数据
    success:function(res){}//请求成功之后的回调函数
}) 

$.ajax()发起GET请求: 

$.ajax({
  type: 'get',
  url: 'http://www.liulongbin.top:3006/api/getbooks',
  data: { id: 1 }
  success: function(res) {
    console.log(res)
}
})

 $.ajax()发起POST请求:

$.ajax({
  type: 'post',
  url: 'http://www.liulongbin.top:3006/api/getbooks',
  data: { 
     bookname: '水浒传',
     author: '施耐庵',
     publisher: '上海图书出版社'
 },
  success: function(res) {
    console.log(res)
}
})

        在Ajax里面只需要设置type属性就可以改变你的请求方式,你想实现GET请求就把type属性改为'get'或者'GET',如果是post请求,就把type属性改为'post'或者'POST'即可。 

2、XMLHttpRequest方式

老规矩!在开始讲解我们的知识点之前,我们还是需要先了解一下什么是XMLHttpRequest

 XMLHttpRequest(简称xhr)是浏览器提供的JavaScript对象,通过它,可以请求服务器上的数据资源。

了解完毕了我们就开始我们的学习吧! 

2.1、发起GET请求

发送GET请求步骤:

  1. 创建xhr对象
  2. 调用xhr.open()函数  指定请求方式和URL地址
  3. 调用xhr.send()函数   发起Ajax请求
  4. 监听xhr.onreadystatechange事件

 发起不带参数的GET请求:

<script>
        // 1. 创建 XHR 对象
        var xhr = new XMLHttpRequest()
            // 2. 调用 open 函数
        xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
            // 3. 调用 send 函数
        xhr.send()
            // 4. 监听 onreadystatechange 事件
        xhr.onreadystatechange = function() {
            // 监听xhr对象的请求状态readyState;与服务器响应状态status
            if (xhr.readyState === 4 && xhr.status === 200) {
                // 获取服务器响应的数据
                console.log(xhr.responseText)
            }
        }
    </script>

发起带参数的GET请求: 

<script>
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
    xhr.send()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
      }
    }
  </script>

2.2、发起POST请求

 发送POST请求的步骤:

  1. 创建xhr对象
  2. 调用xhr.open()函数
  3. 设置Content-Type属性(固定写法)调用setRequestHeader函数
  4. 调用xhr.send(),同时指定要发送的数据
  5. 监听xhr.onreadystatechange事件 
<script>
    // 1. 创建 xhr 对象
    var xhr = new XMLHttpRequest()
    // 2. 调用 open 函数
    xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
    // 3. 设置 Content-Type 属性
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    // 4. 调用 send 函数
    xhr.send('bookname=水浒传&author=施耐庵&publisher=上海图书出版社')
    // 5. 监听事件
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
      }
    }
  </script>

3、Axios

 还是那个熟悉的味道!开始之前我们还是看看到底什么是Axios

Axios是专注于网络数据请求的库,相比于原生的XMLHttpRequest对象,Axios简单易用。相比于jQuery更急轻量化,只专注于网络数据请求 

所以我们需要先引用axios.js文件

3.1、发起GET请求 

 语法格式:axios.get('url',{params:{/*参数*/}}).then(callback)

<body>
    <button id="btn3">直接使用axios发起GET请求</button>
    <script>
        document.querySelector('#btn3').addEventListener('click', function() {
            var url = 'http://www.liulongbin.top:3006/api/get'
            var paramsData = {
                name: '钢铁侠',
                age: 35
            }
            axios({
                method: 'GET',
                url: url,
                params: paramsData
            }).then(function(res) {
                console.log(res.data)
            })
        })
    </script>
</body>

3.2、 发起POST请求

 语法格式:axios.post('url',{/*参数*/}).then(callback)

<body>
    <button id="btn4">直接使用axios发起POST请求</button>
    <script>
        document.querySelector('#btn4').addEventListener('click', function() {
            axios({
                method: 'POST',
                url: 'http://www.liulongbin.top:3006/api/post',
                data: {
                    name: '娃哈哈',
                    age: 18,
                    gender: '女'
                }
            }).then(function(res) {
                console.log(res.data)
            })
        })
    </script>
</body>

总结

        今天的分享就是这些了哦!各位要好好学习哦!

 

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Java可以使用HTTPClient和HttpURLConnection两种方式来实现GET和POST请求。 使用HTTPClient的方法有两个版本,分别是HTTPClient3.1和HTTPClient4.5.5。HTTPClient3.1位于org.apache.commons.httpclient包下,而HTTPClient4.5.5位于org.apache.http.client包下。这两个版本都提供了对远程URL的操作工具包,可以满足工作需求。 另一种方式是使用HttpURLConnection,它是Java的标准请求方式。可以通过创建HttpURLConnection对象来发送GET和POST请求,并获取响应结果。 以下是使用HTTPClient和HttpURLConnection实现GET和POST请求的示例代码: 使用HTTPClient3.1实现GET请求: ```java HttpClient client = new HttpClient(); GetMethod method = new GetMethod(url); int statusCode = client.executeMethod(method); String response = method.getResponseBodyAsString(); ``` 使用HTTPClient4.5.5实现GET请求: ```java CloseableHttpClient client = HttpClients.createDefault(); HttpGet request = new HttpGet(url); CloseableHttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity()); ``` 使用HttpURLConnection实现GET请求: ```java URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); ``` 使用HTTPClient4.5.5实现POST请求: ```java CloseableHttpClient client = HttpClients.createDefault(); HttpPost request = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); request.setEntity(new UrlEncodedFormEntity(params)); CloseableHttpResponse response = client.execute(request); String result = EntityUtils.toString(response.getEntity()); ``` 使用HttpURLConnection实现POST请求: ```java URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("param1=value1&param2=value2"); writer.flush(); int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); ``` 以上是使用Java实现GET和POST请求方法,可以根据具体需求选择适合的方式来发送请求并获取响应结果。\[1\]\[2\] #### 引用[.reference_title] - *1* [用Java实现GET,POST请求](https://blog.csdn.net/lianzhang861/article/details/80364549)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [JAVA的GET和POST请求实现方式](https://blog.csdn.net/u012513972/article/details/79569888)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值