请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

短链接

老师能更新下源码用新浪或者微信的免费的短链接接口吗, 下面是我看有个同学用的微信短链接接口的方法 ,不知道到导入什么依赖,无法解决。。。那个百度短链接收费太贵了…而且每次点击都要钱…
图片描述
图片描述

public class ShortNetAddressUtil {
static String appid = “你的appid”;
static String appsrcret = “你的appsrcret”;

public static void main(String[] args) {
    String longUrl = "https://baidu.com";
    System.out.println(getShortURL(longUrl));

}

/**
 * 微信根据APPID和APPSECRET获取token
 * 
 * @param appid
 * @param appsrcret
 * @return 返回转换后的短链接
 */
public static String getToken(String appid, String appsrcret) throws Exception {
    // 访问地址
    String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
    String APPID = appid;
    String APPSECRET = appsrcret;
    String request_url = TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
    JSONObject jsonObject = HttpUtils.httpsUtil(request_url, "GET", null);
    if (null != jsonObject) {
        String access_token = jsonObject.getString("access_token");
        return access_token;
    }
    return null;
}

/**
 * 将长链接转为短链接(调用的微信短网址API) 需要token
 * 
 * @param longUrl   需要转换的长链接url
 * @param appid
 * @param appsrcret
 * @return 返回转换后的短链接
 */
public static String getShortURL(String longUrl) {
    ResultBean<String> result = new ResultBean<>();
    String token;
    try {
        token = getToken(appid, appsrcret);
        String uri = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=ACCESS_TOKEN";
        String url = uri.replace("ACCESS_TOKEN", token);
        String param = "{"action":"long2short"," + ""long_url":"" + longUrl + ""}";
        // 调用接口创建菜单
        JSONObject jsonObject = HttpUtils.httpRequest(url, "POST", param);
        System.out.println(jsonObject);
        if (null != jsonObject) {
            result.setCode(jsonObject.getInteger("errcode"));
            result.setData(jsonObject.getString("short_url"));
            return result.getData();
        } else {
            return null;
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

}
图片描述

正在回答

2回答

<!-- 生成短链接的两个jar包 -->
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.45</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.9.1</version>
        </dependency>


public class HttpUtils {
    /**
     * HttpsUtil方法https请求结果返回蔚json类型
     * @param Url http请求地址
     * @param Method http请求类型支持POST GET
     * @param Output
     * @return InputStream转换成JSONObject后返回
     * @throws Exception
     */
    public static JSONObject httpsUtil(String Url, String Method, String Output) throws Exception{
        JSONObject jsonObject = null;
        URL conn_url =  new URL(Url);
        HttpURLConnection conn = (HttpURLConnection) conn_url.openConnection();
        conn.setRequestMethod(Method);
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.connect();
        //output获取access_token是不会用到
        if(Output != null){
            OutputStream outputstream =conn.getOutputStream();
            //字符集,防止出现中文乱码
            outputstream.write(Output.getBytes("UTF-8"));
            outputstream.close();
        }
        //正常返回代码为200
        if(conn.getResponseCode()==200){
            InputStream stream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(stream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            stream.close();
            conn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        }
        System.out.println(conn.getResponseCode());
        return jsonObject;
    }
 
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr)   {
        HttpsURLConnection httpUrlConn = null;
        OutputStream outputStream = null ;
        InputStream inputStream = null;
 
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        // 创建SSLContext对象,并使用我们指定的信任管理器初始化
        TrustManager[] tm = { new MyX509TrustManager() };
        try{
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
 
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);
 
            httpUrlConn.connect();
 
            // 当有数据需要提交时
            if (null != outputStr) {
                outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
 
            // 将返回的输入流转换成字符串
            inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
 
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            jsonObject = JSONObject.parseObject(buffer.toString());
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            // 释放资源
            try {
                if(inputStream != null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            inputStream = null;
            if (httpUrlConn != null ){
                httpUrlConn.disconnect();
            }
        }
        return jsonObject;
    }
}

0 回复 有任何疑惑可以回复我~
  • 提问者 大尾鲈鳗100 #1
    感谢大哥 
    还有那个ResultBean<String> result = new ResultBean<>(); 报错怎么解决
    回复 有任何疑惑可以回复我~ 2020-04-16 23:39:30
  • 提问者 大尾鲈鳗100 #2
    是不是还有个ResultBean的类
    回复 有任何疑惑可以回复我~ 2020-04-16 23:44:58
  • 翔仔 #3
    感谢同学的分享,请问同学是否可以调整成和我们视频里的接口一样的方法去获取,然后提交到代码里,感激不尽:)
    回复 有任何疑惑可以回复我~ 2020-04-17 11:07:32
提问者 大尾鲈鳗100 2020-04-16 23:41:39

https://img1.sycdn.imooc.com/szimg/5e987c99098519c000000000.jpg这个呢

1 回复 有任何疑惑可以回复我~
  • 提问者 大尾鲈鳗100 #1
    public class ResultBean<T> implements Serializable {
         private static final long serialVersionUID=1L;
     
         public static final int SUCESS=0;
     
         public static final int FAIL=1;
     
         public String getMsg() {
             return msg;
         }
     
         public void setMsg(String msg) {
             this.msg = msg;
         }
     
         public int getCode() {
             return code;
         }
     
         public void setCode(int code) {
             this.code = code;
         }
     
         public T getData() {
             return data;
         }
     
         public void setData(T data) {
             this.data = data;
         }
     
         public static final int NO_PERMESSION=2;
     
         private String msg="SUCESS";
     
         private int code=SUCESS;
     
     
     
         private T data;
     
         public ResultBean(){
             super();
         }
     
         public ResultBean(T data){
             super();
             this.data=data;
         }
     
         public ResultBean(Throwable e){
             super();
             this.msg=e.toString();
             this.code=FAIL;
         }
     }
    回复 有任何疑惑可以回复我~ 2020-04-17 00:17:50
  • import java.io.Serializable;
    
    public class ResultBean<T> implements Serializable {
        public static final int SUCCESS = 0;
        public static final int FAIL = -1;
    
        private String msg = "SUCCESS";
        private int code = SUCCESS;
        private T data;
    
        public ResultBean() {
            super();
        }
    
        public ResultBean(T data) {
            super();
            this.data = data;
        }
    
        public ResultBean(Throwable e) {
            super();
            this.msg = e.getMessage();
            this.code = FAIL;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public int getCode() {
            return code;
        }
    
        public void setCode(int code) {
            this.code = code;
        }
    
        public T getData() {
            return data;
        }
    
        public void setData(T data) {
            this.data = data;
        }
    }
    回复 有任何疑惑可以回复我~ 2020-04-17 09:27:52
  • 提问者 大尾鲈鳗100 回复 慕用6592966 #3
    感谢大哥的帮助,我昨晚就可以了跑出二维码的了,谢谢
    回复 有任何疑惑可以回复我~ 2020-04-17 09:47:26
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信