如何利用百度短鏈接接口將一個長鏈接變成短鏈接

短網址服務可以幫助你把一個長網址縮短,方便你在社交網絡和第三方平臺上分享鏈接,投放廣告等等。 我們提供超簡單的方式使用短網址服務:訪問百度短網址首頁https://dwz.cn,輸入你要縮短的原網址,生成對應的短網址。你還可以調用百度短網址服務API服務,查看數據統計與分析……更多功能,等你來探索!

官方文檔:https://dwz.cn/console/apidoc
首先添加依賴

<dependency>
 <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.5</version>
</dependency>

然後去百度官方文檔https://dwz.cn/console/apidoc複製示例

package com.imooc.myo2o.util.baidu;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

public class BaiduDwz {
    final static String CREATE_API = "https://dwz.cn/admin/v2/create";
    final static String TOKEN = "你的token"; // TODO:設置Token

    class UrlResponse {
        @SerializedName("Code")
        private int code;

        @SerializedName("ErrMsg")
        private String errMsg;

        @SerializedName("LongUrl")
        private String longUrl;

        @SerializedName("ShortUrl")
        private String shortUrl;

        public int getCode() {
            return code;
        }

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

        public String getErrMsg() {
            return errMsg;
        }

        public void setErrMsg(String errMsg) {
            this.errMsg = errMsg;
        }

        public String getLongUrl() {
            return longUrl;
        }

        public void setLongUrl(String longUrl) {
            this.longUrl = longUrl;
        }

        public String getShortUrl() {
            return shortUrl;
        }

        public void setShortUrl(String shortUrl) {
            this.shortUrl = shortUrl;
        }
    }

    /**
     * 創建短網址
     *
     * @param longUrl
     *            長網址:即原網址
     * @return  成功:短網址
     *          失敗:返回空字符串
     */
    public static String createShortUrl(String longUrl) {
        String params = "{\"url\":\""+ longUrl + "\"}";

        BufferedReader reader = null;
        try {
            // 創建連接
            URL url = new URL(CREATE_API);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 設置請求方式
            connection.setRequestProperty("Content-Type", "application/json"); // 設置發送數據的格式
            connection.setRequestProperty("Token", TOKEN); // 設置發送數據的格式");

            // 發起請求
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8編碼
            out.append(params);
            out.flush();
            out.close();

            // 讀取響應
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            String res = "";
            while ((line = reader.readLine()) != null) {
                res += line;
            }
            reader.close();

            // 抽取生成短網址
            UrlResponse urlResponse = new Gson().fromJson(res, UrlResponse.class);
            if (urlResponse.getCode() == 0) {
                return urlResponse.getShortUrl();
            } else {
                System.out.println(urlResponse.getErrMsg());
            }

            return ""; // TODO:自定義錯誤信息
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
        return ""; // TODO:自定義錯誤信息
    }

    public static void main(String[] args) {
        String res = createShortUrl("你的長網址");
        System.out.println(res);

    }
}

把代碼中的token換成你的token
在官方文檔https://dwz.cn/console/apidoc中獲取token
在這裏插入圖片描述
在這裏插入圖片描述
到此就ok了,可以在main方法中試一下效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章