Java调用百度短网址生成短链接

1. 方式一 直接在线生成 

             https://dwz.cn/

   Java调用百度短网址生成短链接_第1张图片

 

 

 

2. 方式二 调用接口生成

   引入gson-2.8.5.jar   

   可以通过maven仓库搜索下载地址 

   http://central.maven.org/maven2/com/google/code/gson/gson/2.8.5/gson-2.8.5.jar

import com.google.gson.annotations.SerializedName;

/**
 * @program: javaTest1.8
 * @description: 响应结果
 * @author: Mr.Wang
 * @create: 2019-05-31 12:56
 **/
public class UrlResponse {
    //@SerializedName注解来将对象里的属性跟json里字段对应值匹配起来。


    @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;
    }

}

    

public enum StatusCodeEnum {

    // 0:正常返回短网址  -1:短网址生成失败 -2:长网址不合法  -3:长网址存在安全隐患 -4:长网址插入数据库失败 -5:长网址在黑名单中,不允许注册
    NORMAl(0,"正常"),
    FAIL(-1,"短网址生成失败"),
    WRONGFUL(-2,"长网址不合法"),
    NOTSAFE(-3,"长网址存在安全隐患"),
    INSERTFAIL(-4,"长网址插入数据库失败"),
    BLACKLIST(-5,"长网址在黑名单中,不允许注册")
    ;


    private Integer code;

    private String message;



    public Integer getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    StatusCodeEnum(Integer code, String message) {
        this.code = code;
        this.message = message;
    }




}

 

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;

/**
 * @program: javaTest1.8
 * @description: 百度短网址生成接口
 * @author: Mr.Wang
 * @create: 2019-05-31 12:51
 **/
public class BaiduDwz {
    final static String CREATE_API = "https://dwz.cn/admin/v2/create";
    final static String TOKEN = "你的token"; // TODO:设置Token
 
    /**
     * 创建短网址
     *
     * @param longUrl
     *            长网址:即原网址
     * @return  成功:短网址
     *          失败:返回对于的错误信息
     */
    public static String createShortUrl(String longUrl) {
        String params = "{\"url\":\""+ longUrl + "\"}";
        String msg=null;
        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();

            // 利用gson将字符串转换成对象
            UrlResponse urlResponse = new Gson().fromJson(res, UrlResponse.class);
            if (urlResponse.getCode() == 0) {
                msg = urlResponse.getShortUrl();
            } else {
                //循环输出值
                for (StatusCodeEnum e : StatusCodeEnum.values()) {
                    if (urlResponse.getCode() == e.getCode() ){
                         msg =e.getMessage();
                    }
                }

            }

            //return ""; // TODO:自定义错误信息

        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
        //return ""; // TODO:自定义错误信息
        return msg;
    }

    public static void main(String[] args) {
        String res = createShortUrl("http://news.cctv.com/2019/05/30/ARTIKUzYcEgVHC4KFr2pbNo9190530.shtml");
        // https://dwz.cn/1xgMBFRV
        System.out.println(res);

    }

}

 

转载于:https://my.oschina.net/shanesen/blog/3056475

你可能感兴趣的:(Java调用百度短网址生成短链接)