|

分享源码
界面截图: |
|
是否带模块: |
纯源码 |
备注说明: |
- |
- 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));
- }
- }
复制代码
|
|