1. 程式人生 > 實用技巧 >v-if的作用—根據表示式的布林值切換元素的顯示與隱藏(操作dom)

v-if的作用—根據表示式的布林值切換元素的顯示與隱藏(操作dom)

參考的github

使用物件封裝http請求的結果

public class HttpClientResult implements Serializable {

	private static final long serialVersionUID = 2168152194164783950L;

	/**
	 * 響應狀態碼
	 */
	private int code;

	/**
	 * 響應資料
	 */
	private String content;

	public HttpClientResult() {
	}

	public HttpClientResult(int code) {
		this.code = code;
	}

	public HttpClientResult(String content) {
		this.content = content;
	}

	public HttpClientResult(int code, String content) {
		this.code = code;
		this.content = content;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	@Override
	public String toString() {
		return "HttpClientResult [code=" + code + ", content=" + content + "]";
	}

}

編寫工具類

public class HttpClientUtils {

    // 編碼格式。傳送編碼格式統一用UTF-8
    private static final String ENCODING = "UTF-8";

    // 設定連線超時時間,單位毫秒。
    private static final int CONNECT_TIMEOUT = 6000;

    // 請求獲取資料的超時時間(即響應時間),單位毫秒。
    private static final int SOCKET_TIMEOUT = 6000;

    /**
     * 傳送get請求;不帶請求頭和請求引數
     *
     * @param url 請求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url) throws Exception {
        return doGet(url, null, null);
    }

    /**
     * 傳送get請求;帶請求引數
     *
     * @param url    請求地址
     * @param params 請求引數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, null, params);
    }

    /**
     * 傳送get請求;帶請求頭和請求引數
     *
     * @param url     請求地址
     * @param headers 請求頭集合
     * @param params  請求引數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 建立httpClient物件
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 建立訪問的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }

        // 建立http物件
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        /**
         * setConnectTimeout:設定連線超時時間,單位毫秒。
         * setConnectionRequestTimeout:設定從connect Manager(連線池)獲取Connection
         * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連線池的。
         * setSocketTimeout:請求獲取資料的超時時間(即響應時間),單位毫秒。 如果訪問一個介面,多少時間內無法返回資料,就直接放棄此次呼叫。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpGet.setConfig(requestConfig);

        // 設定請求頭
        packageHeader(headers, httpGet);

        // 建立httpResponse物件
        CloseableHttpResponse httpResponse = null;

        try {
            // 執行請求並獲得響應結果
            return getHttpClientResult(httpResponse, httpClient, httpGet);
        } finally {
            // 釋放資源
            release(httpResponse, httpClient);
        }
    }

    /**
     * 傳送post請求;不帶請求頭和請求引數
     *
     * @param url 請求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url) throws Exception {
        return doPost(url, null, null);
    }

    /**
     * 傳送post請求;帶請求引數
     *
     * @param url    請求地址
     * @param params 引數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
        return doPost(url, null, params);
    }

    /**
     * 傳送post請求;帶請求頭和請求引數
     *
     * @param url     請求地址
     * @param headers 請求頭集合
     * @param params  請求引數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 建立httpClient物件
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 建立http物件
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout:設定連線超時時間,單位毫秒。
         * setConnectionRequestTimeout:設定從connect Manager(連線池)獲取Connection
         * 超時時間,單位毫秒。這個屬性是新加的屬性,因為目前版本是可以共享連線池的。
         * setSocketTimeout:請求獲取資料的超時時間(即響應時間),單位毫秒。 如果訪問一個介面,多少時間內無法返回資料,就直接放棄此次呼叫。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        // 設定請求頭
		/*httpPost.setHeader("Cookie", "");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
        packageHeader(headers, httpPost);

        // 封裝請求引數
        packageParam(params, httpPost);

        // 建立httpResponse物件
        CloseableHttpResponse httpResponse = null;

        try {
            // 執行請求並獲得響應結果
            return getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            // 釋放資源
            release(httpResponse, httpClient);
        }
    }

    /**
     * 傳送put請求;不帶請求引數
     *
     * @param url    請求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPut(String url) throws Exception {
        return doPut(url);
    }

    /**
     * 傳送put請求;帶請求引數
     *
     * @param url    請求地址
     * @param params 引數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPut.setConfig(requestConfig);

        packageParam(params, httpPut);

        CloseableHttpResponse httpResponse = null;

        try {
            return getHttpClientResult(httpResponse, httpClient, httpPut);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 傳送delete請求;不帶請求引數
     *
     * @param url    請求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpDelete.setConfig(requestConfig);

        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpDelete);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 傳送delete請求;帶請求引數
     *
     * @param url    請求地址
     * @param params 引數集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
        if (params == null) {
            params = new HashMap<String, String>();
        }

        params.put("_method", "delete");
        return doPost(url, params);
    }


    /**
     * 傳送上傳檔案請求;
     *
     * @param url      請求地址
     * @param params   引數集合
     * @param headers  請求頭集合
     * @param filePath 檔案路徑
     * @param fileType 檔案型別名
     * @return
     * @throws Exception
     */
    public static HttpClientResult uploadFile(String url,
                                              Map<String, String> params,
                                              Map<String, String> headers,
                                              String filePath,
                                              String fileType) throws Exception {
        final CloseableHttpClient httpClient = HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "multipart/form-data");
        packageHeader(headers, httpPost);
        //建立multipart/form-data的entity的builder
        final MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //將檔案加在http的post請求中
        final File file = new File(filePath);
        builder.addBinaryBody(
                fileType,
                new FileInputStream(file),
                ContentType.APPLICATION_OCTET_STREAM,
                file.getName()
        );
        if (params != null) {
            final JSONObject jsonObject = new JSONObject();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                jsonObject.put(entry.getKey(), entry.getValue());
            }
            builder.addTextBody(jsonObject.toString(), ContentType.APPLICATION_JSON.toString());
        }
        //生成multipart/form-data的entity
        final HttpEntity multipartEntity = builder.build();
        httpPost.setEntity(multipartEntity);
        CloseableHttpResponse response = null;
        try {
            return getHttpClientResult(response, httpClient, httpPost);
        }finally {
            release(response,httpClient);
        }
    }

    /**
     * Description: 封裝請求頭
     *
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封裝請求頭
        if (params != null) {
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                // 設定到請求頭到HttpRequestBase物件中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封裝請求引數
     *
     * @param params
     * @param httpMethod
     * @throws UnsupportedEncodingException
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
            throws UnsupportedEncodingException {
        // 封裝請求引數
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            Set<Entry<String, String>> entrySet = params.entrySet();
            for (Entry<String, String> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }

            // 設定到請求的http物件中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }

    /**
     * Description: 獲得響應結果
     *
     * @param httpResponse
     * @param httpClient
     * @param httpMethod
     * @return
     * @throws Exception
     */
    public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
                                                       CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
        // 執行請求
        httpResponse = httpClient.execute(httpMethod);

        // 獲取返回結果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            String content = "";
            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
            return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

    /**
     * Description: 釋放資源
     *
     * @param httpResponse
     * @param httpClient
     * @throws IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        // 釋放資源
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }

}

傳送請求至httpbin進行測試

httpbin