您的位置:首页 > 移动开发 > Android开发

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

2015-12-10 19:17 330 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: