短链接的生成之工具类的编写--三种方式(亲测可用)

在很多时候我们都需要使用到短链接,比较常见的是在生成微信二维码的时候,长的url不能生成二维码,必须使用短链接。所以短链接的生成就尤其重要,废话不多说,下面直接介绍三种生成短链接的工具类

一、使用百度的短链接服务生成短链接 (可能不太稳定,时而能获取二维码 时而不能获取)

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ShortNetAddressUtil {
    private static Logger log = LoggerFactory.getLogger(ShortNetAddressUtil.class);


    public static int TIMEOUT = 30 * 1000;
    public static String ENCODING = "UTF-8";


    /**
     * 根据传入的url,通过访问百度短链接的接口, 将其转换成短的URL
     *
     * @param originURL
* @return
*/
public static String getShortURL(String originURL) {
        String tinyUrl = null;
        try {
            // 指定百度短链接的接口
URL url = new URL("http://dwz.cn/create.php");
            // 建立连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设置连接的参数
            // 使用连接进行输出
connection.setDoOutput(true);
            // 使用连接进行输入
connection.setDoInput(true);
            // 不使用缓存
connection.setUseCaches(false);
            // 设置连接超时时间为30秒
connection.setConnectTimeout(TIMEOUT);
            // 设置请求模式为POST
connection.setRequestMethod("POST");
            // 设置POST信息,这里为传入的原始URL
String postData = URLEncoder.encode(originURL.toString(), "utf-8");
            // 输出原始的url
connection.getOutputStream().write(("url=" + postData).getBytes());
            // 连接百度短视频接口
connection.connect();
            // 获取返回的字符串
String responseStr = getResponseStr(connection);
            log.info("response string: " + responseStr);
            // 在字符串里获取tinyurl,即短链接
tinyUrl = getValueByKey(responseStr, "tinyurl");
            log.info("tinyurl: " + tinyUrl);
            // 关闭链接
connection.disconnect();
        } catch (IOException e) {
            log.error("getshortURL error:" + e.toString());
        }
        return tinyUrl;
    }


    /**
     * 通过HttpConnection 获取返回的字符串
     *
     * @param connection
* @return
* @throws IOException
     */
private static String getResponseStr(HttpURLConnection connection) throws IOException {
        StringBuffer result = new StringBuffer();
        // 从连接中获取http状态码
int responseCode = connection.getResponseCode();


        if (responseCode == HttpURLConnection.HTTP_OK) {
            // 如果返回的状态码是OK的,那么取出连接的输入流
InputStream in = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, ENCODING));
            String inputLine = "";
            while ((inputLine = reader.readLine()) != null) {
                // 将消息逐行读入结果中
result.append(inputLine);
            }
        }
        // 将结果转换成String并返回
return String.valueOf(result);
    }


    /**
     * JSON 依据传入的key获取value
     *
     * @param replyText
* @param key
* @return
*/
private static String getValueByKey(String replyText, String key) {
        ObjectMapper mapper = new ObjectMapper();
        // 定义json节点
JsonNode node;
        String targetValue = null;
        try {
            // 把调用返回的消息串转换成json对象
node = mapper.readTree(replyText);
            // 依据key从json对象里获取对应的值
targetValue = node.get(key).asText();
        } catch (JsonProcessingException e) {
            log.error("getValueByKey error:" + e.toString());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("getValueByKey error:" + e.toString());
        }


        return targetValue;
    }


    /**
     *  百度短链接接口
     *
     * @param args
*/
public static void main(String[] args) {
        getShortURL("https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login");
    }
}

 

二、仍然是百度的短链接服务,不过是另一种方式。

(这种方式获取二维码较稳定,不过在扫码的时候有可能会出现scope不能为空的错误信息)

这种方式需要加入两个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>
 
import java.io.IOException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ShortNetAddressUtil {
    public static String getShortURL(String longUrl) {
        try {
            String result = callHttp("http://suo.im/api.php?format=json&url=" + longUrl);
            JSONObject jsonResult = JSON.parseObject(result);
            return jsonResult.getString("url");
        } catch (IOException e) {
            // TODO Auto-generated catch block
e.printStackTrace();
            return null;
        }
    }

    private static String callHttp(String requestUrl) throws IOException {
        OkHttpClient httpClient = new OkHttpClient(); // 创建OkHttpClient对象
Request request = new Request.Builder().url(requestUrl)// 请求接口。如果需要传参拼接到接口后面。
.build();// 创建Request 对象
Response response = null;
        response = httpClient.newCall(request).execute();// 得到Response 对象
return response.body().string();
    }

    /**
     * 百度短链接接口
     *
     * @param args
*/
public static void main(String[] args) {
        System.out.println(getShortURL("https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login"));
    }
}

三、使用新浪的短服务生成短链接 (个人觉得目前这种方式最稳定)

同样需要使用到两个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>

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * 使用新浪的短链接服务生成短链接
 */
public class ShortNetAddressUtil{


    static String actionUrl = "http://api.t.sina.com.cn/short_url/shorten.json";
    static String APPKEY = "2815391962,31641035,3271760578,3925598208";
    public static void main(String[] args) {
        String longUrl = "https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login";
        System.out.println(getShortURL(longUrl));
    }



    public static String getShortURL(String longUrl){

        longUrl = java.net.URLEncoder.encode(longUrl);
        String appkey = APPKEY;
        String[] sourceArray = appkey.split(",");
        for(String key:sourceArray){
            String shortUrl = sinaShortUrl(key,longUrl);
            if(shortUrl != null){
                return shortUrl;
            }
        }
        return null;
    }

    public static String sinaShortUrl(String source, String longUrl){
        String result = sendPost(actionUrl, "url_long="+longUrl+"&source="+source);
        if(result==null || "".equals(result)){
            return "";
        }

        JSONArray jsonArr = JSON.parseArray(result);
        JSONObject json = JSON.parseObject(jsonArr.get(0).toString());
        String ret = json.get("url_short").toString();
        return ret;
    }


    /**
     * 向指定 URL 发送POST方法的请求
     * @param url 发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
public static String sendPost(String url, String param) {

        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // 发送POST请求必须设置如下两行
conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());

            // 发送请求参数
out.print(param);
            // flush输出流的缓冲
out.flush();
            // 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!"+e);
            e.printStackTrace();
        }

        //使用finally块来关闭输出流、输入流
finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }

            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
}

以上就是短链接的生成的工具类的三种编写方式,各个公司的短链接服务有时候稳定有时候不稳定,比如前段时间百度的短链接服务就不是很稳定。所以大家可以在实际应用过程中挑选三种不同的方法来进行选择。

 

posted @ 2018-04-15 17:11  宇宙间的星河集  阅读(949)  评论(0编辑  收藏  举报