首页 > 编程 > Java > 正文

调用百度短网址API接口进行短网址的转换(Java程序的实现)

2019-11-06 08:55:18
字体:
来源:转载
供稿:网友

1、功能说明:把需要给用户发的短信:

您周围已有39位同行入驻买卖网, 生存危机一触即发,买卖网流量不容错过,即刻享受流水0抽成!详情查看:http://baidu.com/?ch=mt&mId=jU5LVV 回复TD退订";中的url转换为短网址形式,转换后短信内容为:"您周围已有39位同行入驻买卖网, 生存危机一触即发,买卖网流量不容错过,即刻享受流水0抽成!详情查看:http://dwz.cn/5pHynG 回复TD退订"

2、现实思路:首先将短信内容中的url提取出来,然后调用短网址接口,将该url转换为短网址,最后将转换后的短网址url替换原来短信内容中的url;

3、java程序如下:(需要导入阿里的json包:fastjson-1.1.28.jar)

通过http post方式实现:

package shortUrl;import java.nio.charset.Charset;import java.util.regex.Matcher;import java.util.regex.Pattern;import net.sf.json.JSONObject;import org.apache.http.client.fluent.Content;import org.apache.http.client.fluent.Form;import org.apache.http.client.fluent.Request;/** *  * 短网址转换类  *  */public class GenerateShortUrl {	PRivate static String url =  "http://dwz.cn/create.php";	// 短网址转换的post请求体	private static String generateShortUrl(String oldUrl) {		try {			Content resp = Request					.Post(url)					.bodyForm(							Form.form()							.add("url", oldUrl)							.build(),							Charset.forName("UTF-8")).execute().returnContent();			String respString = resp.asString();            System.out.println(respString); 			JSONObject jsonObject = JSONObject.fromObject(respString); 			oldUrl = jsonObject.getString("tinyurl");						//JSONObject object = JSON.parSEObject(respString);			//System.out.println(object);						//oldUrl = object.getString("tinyurl");						return oldUrl;					} catch (Exception e) {			return oldUrl;		}					}	/**	 * 短网址转换入口函数	 * 	 */	public static void main(String[] args) {				String strBody = "您周围已有39位同行入驻买卖网, 生存危机一触即发,买卖网流量不容错过,即刻享受流水0抽成!详情查看:http://baidu.com/?ch=mt&mId=jU5LVV 回复TD退订";				 Pattern pattern = Pattern.compile("(http://[///.//w//?=&-]+)");	        Matcher matcher = pattern.matcher(strBody);	        String oldUrl = null;	        while (matcher.find()) {	        	oldUrl = matcher.group();	        }	        //要转换的url为空或者长度小于20不进行转换			if (null == oldUrl || oldUrl.length() <= 20 ){				System.out.println(oldUrl);			}	        System.out.println(oldUrl);			String shortUrl = generateShortUrl(oldUrl);			System.out.println(shortUrl);			String newStrBody = strBody.replaceAll("(?is)(?<!')(http://[///.//w//?=&-]+)", shortUrl);			System.out.println(newStrBody);			}}

输出结果:

http://baidu.com/?ch=mt&mId=jU5LVV

{"tinyurl":"http:////dwz.cn//5pHynG","status":0,"longurl":"http://baidu.com/?ch=mt&mId=jU5LVV","err_msg":""}

http://dwz.cn/5pHynG

您周围已有39位同行入驻买卖网, 生存危机一触即发,百度流量不容错过,即刻享受流水0抽成!详情查看:http://dwz.cn/5pHynG 回复TD退订


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表