Android使用bit.ly的api获取url 短连接

bit.ly相比起twitter和google的短连接服务,使用起来更为简单(谷歌的弄了一晚上也没弄出来)而且使用的是get方法,测试和上手都比较容易,下面是使用android 原生类写的通过长url获取短连接的方法,拷贝过去就可以直接用了,而且附赠我自己申请的key,免除诸位申请key的麻烦。

但是把长连接换成短连接有什么用我还没看出来,至少在twitter上发东西twitter会自动帮你转的,完全不用手动转。

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo; 
    public static final String DEF_CHATSET = "UTF-8";//默认字符编码
    public static final int DEF_CONN_TIMEOUT = 30000;//默认超时连接时间
    public static final int DEF_READ_TIMEOUT = 30000;//默认下载连接时间
    public static final String GET = "GET";
    public static final String POST = "POST";
    public static final String BITLY_CODE = "3ae922985a170d3a7cc3e6e7e55b980b413e34e6";//bit.ly的KEY
    //客户端浏览器类型
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    public static String get(String strUrl,Map<String, Object> params,String flag){
        return net(strUrl, params, GET, flag);
    }
    public static String post(String strUrl,Map<String, Object> params,String flag){
        return net(strUrl, params, POST, flag);
    }
    @SuppressLint("NewApi")//警告:如果url连接失败返回为null!!!
    private static String net(String strUrl, Map<String, Object> params,String method,String flag) {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if(method==null || method.equals("GET")){
                if(params!=null&¶ms.size()>0)//如果有参数
                    strUrl = strUrl+"?"+urlencode(params);//捎带手把字符给照url编码
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if(method==null || method.equals("GET")){
                conn.setRequestMethod("GET");
            }else{
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);//连接超时时间
            conn.setReadTimeout(DEF_READ_TIMEOUT);//下载超时时间
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (method.equals("POST")) {
                if(params!= null &¶ms.size()>0)
                    try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                        out.writeBytes(urlencode(params));
                        out.flush();
                        out.close();
                    }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));//设置解析编码
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
        } catch (IOException e) {
            JLogUtils.i("Alex", flag + "网络连接失败");
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    JLogUtils.i("Alex",flag + "连接关闭失败");
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rs;//如果失败返回为null
    }

    //将map型转为请求参数型
    public static String urlencode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"",DEF_CHATSET)).append("&");//按照默认参数对字符进行编码
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public static String getShortUrl(String longUrl){
//        https://api-ssl.bitly.com/v3/user/link_save?access_token=3ae922985a170d3a7cc3e6e7e55b980b413e34e6&longUrl=www.baidu.com
        JLogUtils.i("Alex", "压缩前网址为" + longUrl);
        longUrl.replace("?", "/?");
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("longUrl",longUrl);
        params.put("access_token",BITLY_CODE);
        String shortUrl = get("https://api-ssl.bitly.com/v3/user/link_save",params,"获取短连接");
        JLogUtils.i("Alex","获取的短连接为"+shortUrl);
//        {
//            "data": {
//            "link_save": {
//                "aggregate_link": "http://bit.ly/JGVkUl",
//                        "link": "http://bit.ly/JGVkUk",
//                        "long_url": "http://mergerecords.com/news",
//                        "new_link": 1
//            }
//        },
//            "status_code": 200,
//                "status_txt": "OK"
//        }

        try {
            JSONObject returnObject = new JSONObject(shortUrl);
            JSONObject data = returnObject.getJSONObject("data");
            JSONObject save = data.getJSONObject("link_save");
            shortUrl = save.getString("link");
            JLogUtils.i("Alex","最终获得的短连接为"+shortUrl);
        } catch (JSONException e) {
            JLogUtils.i("Alex","短url返回Json格式异常"+shortUrl);
            e.printStackTrace();
        }

        if(JDataUtils.isEmpty(shortUrl))return longUrl;
        return shortUrl;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值