短链接是个好东西,用在短信里省了不少文字。新浪微博API提供短链接的接口,但要申请weibo appkey ,一下子搞清楚什么是oAuth2.0,估计折腾一段时间。有现成的网页转换地址 http://www.henshiyong.com/tools/sina-shorten-url.php ,在此基础上修改即可。
用浏览器查看 的代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset="UTF-8" />
<title>在线版新浪微博短链接生成器</title>
<meta name="description" content="短链接生成器,新浪微博短连接生成器,在线版新浪微短连接生成,方便快捷完成您的URL转换!" />
<meta name="keywords" content="短链接生成器,新浪微博短连接生成器,在线版新浪微短连接生成" />
<style type="text/css">
textarea{border:5px solid;border-radius:8px 8px 0 0;width:400px;padding:8px;}
body{text-align:center;margin:150px auto;}
</style>
</head>
<body>
<h2>请输入你需要转换的网页地址</h2>
<form action="" method="post">
<input type="" name="url" style="width:400px"/><br/>
<input type="submit" value="转换" name="submit">
</form>
</body>
</html>
小部队先上,用Ruby写个简单脚本,发 POST 请求。
#!/usr/bin/ruby
#
# encoding: utf-8
#
# Make long url into short url from http://t.cn
#
require "uri"
require "net/http"
params = {
'url' => 'http://www.google.com',
'submit' => '转换'
}
x = Net::HTTP.post_form(URI.parse('http://www.henshiyong.com/tools/sina-shorten-url.php'), params)
puts x.body
[deli@violet ~]$ ruby sina-shorten-url.rb
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset="UTF-8" />
<title>在线版新浪微博短链接生成器</title>
<meta name="description" content="短链接生成器,新浪微博短连接生成器,在线版新浪微短连接生成,方便快捷完成您的URL转换!" />
<meta name="keywords" content="短链接生成器,新浪微博短连接生成器,在线版新浪微短连接生成" />
<style type="text/css">
textarea{border:5px solid;border-radius:8px 8px 0 0;width:400px;padding:8px;}
body{text-align:center;margin:150px auto;}
</style>
</head>
<body>
<h2>新浪短连接已经生成:</h2><textarea>http://t.cn/h51yw</textarea><h2>继续转换 </h2></body>
</html>
提取 textarea 标签数据即可,使用正则表达式最方便的了。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ShortenUrl {
private static final boolean DEBUG = true;
public static void main(String[] args) {
String url = "http://www.henshiyong.com/tools/sina-shorten-url.php";
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("url", "http://www.google.com");
params.put("submit", "转换");
String data = null;
try {
data = postUrl(url, params);
if (DEBUG) {
System.out.println(data);
}
} catch (IOException ex) {
}
if (data != null) {
String shortUrl = getShortenUrl(data);
if (DEBUG) {
System.out.println(shortUrl);
}
}
}
public static String getShortenUrl(String content) {
String url = null;
List<String> resultList = getContext(content);
for (Iterator<String> iterator = resultList.iterator(); iterator.hasNext();) {
url = iterator.next();
}
return url;
}
/**
* Extract "XXXX" from "<textarea>XXXX</textarea>"
* @param html
* @return
*/
public static List<String> getContext(String html) {
List<String> resultList = new ArrayList<String>();
Pattern p = Pattern.compile("<textarea>(.*)</textarea>");
Matcher m = p.matcher(html);
while (m.find()) {
resultList.add(m.group(1));
}
return resultList;
}
public static class HttpException extends RuntimeException {
private int errorCode;
private String errorData;
public HttpException(int errorCode, String errorData) {
super("HTTP Code "+errorCode+" : "+errorData);
this.errorCode = errorCode;
this.errorData = errorData;
}
public int getErrorCode() {
return errorCode;
}
public String getErrorData() {
return errorData;
}
}
public static String postUrl(String url, Map<String, String> params) throws IOException {
String data = "";
for (String key : params.keySet()) {
data += "&"+URLEncoder.encode(key, "UTF-8") + "="
+ URLEncoder.encode(params.get(key), "UTF-8");
}
data = data.substring(1);
//System.out.println(data);
URL aURL = new java.net.URL(url);
HttpURLConnection aConnection = (java.net.HttpURLConnection) aURL
.openConnection();
try {
aConnection.setDoOutput(true);
aConnection.setDoInput(true);
aConnection.setRequestMethod("POST");
//aConnection.setAllowUserInteraction(false);
// POST the data
OutputStreamWriter streamToAuthorize = new java.io.OutputStreamWriter(
aConnection.getOutputStream());
streamToAuthorize.write(data);
streamToAuthorize.flush();
streamToAuthorize.close();
// check error
int errorCode = aConnection.getResponseCode();
if(errorCode >= 400) {
InputStream errorStream = aConnection.getErrorStream();
try {
String errorData = streamToString(errorStream);
throw new HttpException(errorCode,errorData);
} finally {
errorStream.close();
}
}
// Get the Response
InputStream resultStream = aConnection.getInputStream();
try {
String responseData = streamToString(resultStream);
return responseData;
} finally {
resultStream.close();
}
} finally {
aConnection.disconnect();
}
}
private static String streamToString(InputStream resultStream) throws IOException {
BufferedReader aReader = new java.io.BufferedReader(
new java.io.InputStreamReader(resultStream));
StringBuffer aResponse = new StringBuffer();
String aLine = aReader.readLine();
while (aLine != null) {
aResponse.append(aLine+"\n");
aLine = aReader.readLine();
}
return aResponse.toString();
}
}