使用httpclient實現下拉列表動態填充

以上就是咱們須要實現的功能,使用httpclient實現下拉列表的動態填充!!!本案例是基於springboot實現須要有必定的使用基礎,使用spring來實現的話相對來講比較麻煩,咱們都知道html實現異步請求,可使用ajax,那麼咱們java須要後臺實現異步請求可使用httpclient實現,本案例的實現思路以下css

 1.select實現change事件
 2.用ajax將當前選中的城市傳給controller
 3.controller使用httpclient調用高德地圖獲取到區縣信息
 4.responsebody響應ajax請求,
 5.將區縣列表填充到第二個下拉框html

目結構以下java

首先創建springboot項目,不知道怎麼小夥伴能夠參考,本系列教程第一篇springboot入門案例!!jquery

第一種方式:使用httpClient實現

第一步、在pom中導入本次須要的座標依賴

本案例使用了,springboot裏面特定支持的熱部署,不用修改了項目以後不用再次,啓動項目,只須要點擊idea上面的那個錘子就能夠git

實現熱部署很很簡單,只是在pom文件中導入如下座標就好github

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional><!--不能被其它模塊繼承-->
    <scope>runtime</scope><!--只在運行時起做用,打包時不打進去-->
</dependency>
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <!--這個是將對象轉換爲字符串-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit4</artifactId>
            <version>4.11</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>layui</artifactId>
            <version>2.4.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional><!--實現熱部署,不能被其它模塊繼承-->
            <scope>runtime</scope><!--只在運行時起做用,打包時不打進去-->
        </dependency>
    </dependencies>
</project>

第二步、編寫index.html訪問主頁面

前臺的訪問頁面是用的ajax請求實現的,向咱們的後臺的controller傳遞了一個keysword值,在controller頁面進行接收web

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--導入jquery數據包-->
    <script src="webjars/jquery/3.4.1/jquery.min.js"></script>
    <style type="text/css">
        #div1{
            margin: 30px auto;
            width: 300px;
            height: 20px;
            border: 0px solid red;
        }
    </style>
</head>
<body>
<div id="div1">
        省份:
        <select id="province">
            <option value=" ">--請選擇城市--</option>
            <option value="重慶">重慶</option>
            <option value="北京">北京</option>
        </select>
        市區:
        <select id="district">--省份--</select>
    </div>
<script>
    $("#province").change(function () {
        var province=$("#province").val();//獲取選中的值
        $("#district").children().remove();//清空前一次訪問數據
        $.getJSON("doGetControllerOne?keywords="+province,province,function(data){
            var result=data.districts[1].districts;
            $(result).each(function (i,item) {
                var code=item.citycode;
                var name=item.name;
                $("#district").append("<option value="+code+">"+name+"</option>")
            });
        });
    })
</script>
</body>
</html>

第三步、編寫controler控制頁面

這裏有幾點須要詳細講解的地方,這裏涉及到了高德api接口的調用,不會使用的小夥伴們能夠參考個人另一篇博客,高德地圖入門案例,裏面有比較詳細的講解ajax

https://restapi.amap.com/v3/config/district?key=key值&keywords="+keywords+"&subdistrict=1&extensions=base,這個訪問的地址https://lbs.amap.com/api/webservice/guide/api/district/獲取該以上地址,key值是須要你本身去申請spring

keyword裏面能夠修改,然點擊運行能夠生成新的地址,複製到你的new HttpGet裏面apache

package com.cc.springhttpclient.controller;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class doGet {
    @ResponseBody
    @RequestMapping("/doGetControllerOne")
    public String doGetController(HttpServletRequest req, HttpServletResponse rep){
        String keywords=req.getParameter("keywords");
        if(StringUtils.isEmpty(keywords)){
            keywords="重慶";
        }
        System.out.println("省份爲:"+keywords);
        // 得到Http客戶端(能夠理解爲:你得先有一個瀏覽器;注意:實際上HttpClient與瀏覽器是不同的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 建立Get請求,裏面須要放請求的
        HttpGet httpGet = new HttpGet("https://restapi.amap.com/v3/config/district?key=填寫你的key值&keywords="+keywords+"&subdistrict=1&extensions=base");
        // 響應模型
        CloseableHttpResponse response = null;
        try {
            // 由客戶端執行(發送)Get請求
            response = httpClient.execute(httpGet);
            // 從響應模型中獲取響應實體
            HttpEntity responseEntity  = response.getEntity();
            if (responseEntity != null) {
                //System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));?第一次使用的時候會關閉流
                String result=EntityUtils.toString(responseEntity);//解析json數據
                return result;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 釋放資源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

這裏你們有一點須要注意的地方,就是這個toString方法,爲了在控制檯測試我是否獲取到了高德地圖裏面區域信息,我在用sou在控制檯輸出了一下,可是下面框框地方顯示流被關閉了,當時我就很疑惑這是怎麼回事,而後而後點開了toString的源碼一下就明白了!!!

public static void consume(HttpEntity entity) throws IOException {
    if (entity != null) {
        if (entity.isStreaming()) {
            InputStream inStream = entity.getContent();
            if (inStream != null) {
                inStream.close();
            }
        }

    }
}

這是toString裏面的源碼,使用了這個方法以後,流就被關閉了,因此你們在使用這個方法的時候必定要注意!!!!

if (responseEntity != null) {
    System.out.println("響應內容爲:" + EntityUtils.toString(responseEntity));//第一次使用的時候會關閉流
    String result=EntityUtils.toString(responseEntity);//解析json數據
    return result;
}

第四步、啓動測試主類

須要完整項目案例的能夠去個人github上面下載,如下是個人github地址

https://github.com/chenduotang/spring_boot-httpclient

第二種方式:使用RestTemplate實現

那麼RestTemplate和httpclient有什麼區別!!說白了就是對,httpclient的進一步高級封裝,想了解更多有關RestTemplate能夠查看這篇博客

https://blog.csdn.net/u012702547/article/details/77917939/

首先、在config文件中再配置一個RestTemplate的類,交給spring管理

package com.cc.springhttpclient.RestConfig;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestConfig {
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        return restTemplate;
    }
}

其次、在controller層修改代碼以下

package com.cc.springhttpclient.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/***
 * 第二種實現方式,使用RestTemplate實現
 * RestTemplate是對HttpClient的進一步封裝
 */
@Controller
public class doGeto {
    @Autowired
    private RestTemplate restTemplate;

    @ResponseBody
    @RequestMapping("/doGetControllerOnet")
    public String doGetController(HttpServletRequest req, HttpServletResponse rep){
        String keywords=req.getParameter("keywords");
        System.out.println(keywords);
        if(StringUtils.isEmpty(keywords)){
            keywords="重慶";
        }
        String URL="https://restapi.amap.com/v3/config/district?key=你申請的key值&keywords="+keywords+"&subdistrict=1&extensions=base";
        String result = restTemplate.getForObject(URL, String.class);
        return result;
    }
}
相關文章
相關標籤/搜索