精易论坛
标题:
【java】 TX短链接生成
[打印本页]
作者:
junWord
时间:
2020-5-4 12:57
标题:
【java】 TX短链接生成
1.直接导入第三方jar
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20190722</version>
</dependency>
2.工具类代码
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.json.JSONObject;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HttpClientHelper {
public static JSONObject ShortUrl(String UrlLink) throws HttpException, IOException {
String ApiUrl="https://service.weibo.com/share/share.php?url="+UrlLink+"&title=texs";
// 创建httpClient实例对象
HttpClient httpClient = new HttpClient();
// 设置httpClient连接主机服务器超时时间:15000毫秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建post请求方法实例对象
PostMethod postMethod = new PostMethod(ApiUrl);
// 设置post请求超时时间
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
postMethod.addRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
String regex ="scope.short_url = "(.*?) "";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(result);
String ApiText="";
while(matcher.find()){
ApiText = matcher.group(1);
}
Map<String, Object> map = new HashMap<String, Object>();
map.put("Code","200");
map.put("ShortUrl",ApiText.trim());
map.put("LongUrl",UrlLink);
JSONObject jObject = new JSONObject(map);
return jObject;
}
public static void main(String[] args) throws HttpException, IOException {
String url = "http://www.juni.ink";
System.out.println("short_url->"+ShortUrl(url));
}
}
复制代码
作者:
动鸡不淳
时间:
2020-5-4 13:08
我是为了那个回贴奖励才回复的
作者:
junWord
时间:
2020-5-4 13:10
skychat 发表于 2020-5-4 13:08
我是为了那个回贴奖励才回复的
(>^ω^<)感谢支持
作者:
along6
时间:
2020-5-4 14:35
我是为了那个回贴奖励才回复的
作者:
菜就多多练
时间:
2020-5-4 16:58
易语言这么简单我都没搞明白,这个我就不看了
作者:
久居时光
时间:
2020-5-4 23:18
我是为了那个回贴奖励才回复的
作者:
蓝疯子
时间:
2020-5-5 22:58
httpclient读网页 正则取短连接 这个不是新浪的么..
欢迎光临 精易论坛 (https://125.confly.eu.org/)
Powered by Discuz! X3.4