长链接转短连接

 1 package _test;
 2 
 3 import java.util.LinkedList;
 4 import java.util.List;
 5 
 6 import org.apache.http.NameValuePair;
 7 import org.apache.http.client.entity.UrlEncodedFormEntity;
 8 import org.apache.http.client.methods.CloseableHttpResponse;
 9 import org.apache.http.client.methods.HttpPost;
10 import org.apache.http.impl.client.CloseableHttpClient;
11 import org.apache.http.impl.client.HttpClients;
12 import org.apache.http.message.BasicNameValuePair;
13 import org.apache.http.util.EntityUtils;
14 
15 import com.alibaba.fastjson.JSON;
16 import com.alibaba.fastjson.JSONArray;
17 import com.alibaba.fastjson.JSONObject;
18 public class Test_Java {
19     /**
20      * 百度
21      */
22     public static String convert1(String url) {
23         CloseableHttpClient httpClient = HttpClients.createDefault();
24         try {
25             HttpPost post = new HttpPost("http://www.dwz.cn/create.php");
26             List<NameValuePair> params = new LinkedList<NameValuePair>();
27             params.add(new BasicNameValuePair("url", url));
28             post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
29             CloseableHttpResponse response = httpClient.execute(post);
30             String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
31             JSONObject object = JSON.parseObject(jsonStr);
32             return object.getString("tinyurl");
33         } catch (Exception e) {
34             e.printStackTrace();
35             return null;
36         }
37     }
38     /**
39      * 新浪
40      */
41     public static String convert2(String url) {
42         CloseableHttpClient httpClient = HttpClients.createDefault();
43         try {
44             HttpPost post = new HttpPost("http://api.t.sina.com.cn/short_url/shorten.json");
45             List<NameValuePair> params = new LinkedList<NameValuePair>();
46             params.add(new BasicNameValuePair("url_long", url));
47             params.add(new BasicNameValuePair("source", "3271760578"));
48             post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
49             CloseableHttpResponse response = httpClient.execute(post);
50             String json = EntityUtils.toString(response.getEntity(), "utf-8");
51             JSONArray jsonArray = JSONArray.parseArray(json);
52             JSONObject object = (JSONObject) jsonArray.get(0);
53             return object.getString("url_short");
54         } catch (Exception e) {
55             e.printStackTrace();
56             return null;
57         }
58     }
59 }
原文地址:https://www.cnblogs.com/goatherd/p/10844791.html