对接示例
import java.net.URI;
import java.util.List;
import org.bachelor.manager.domain.DwzXinLangResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import cn.com.mwsoft.comm.AESUtil;
import io.swagger.annotations.ApiOperation;
/**
* @author GT 2019年05月16日
*/
@RestController
public class ShortURL {
@Value("${xinlang.createApi:#{null}}")
private String CREATE_API;
@Autowired
RestTemplate restTemplate;
/**
* 创建短网址
*
* @param longUrl 长网址:即原网址
* @return 成功:短网址 失败:返回空字符串
*/
@ApiOperation(value = "短网址生成接口", notes = "短网址生成接口")
@PostMapping(value = "/createShortUrl")
public String createShortUrl(@RequestParam("longUrl") String longUrl) {
// api地址
String address = CREATE_API + "&url_long=" + AESUtil.getURLEncoderString(longUrl);
ResponseEntity<String> forEntity;
String url_short = "";
try {
forEntity = restTemplate.getForEntity(new URI(address), String.class);
String response = forEntity.getBody();
// 抽取生成短网址
List<DwzXinLangResponse> urlResponse = new Gson().fromJson(response,
new TypeToken<List<DwzXinLangResponse>>() {
}.getType());
if (urlResponse != null && urlResponse.size() >= 1) {
url_short = urlResponse.get(0).getUrl_short();
}
} catch (Exception e) {
url_short = "";
}
return url_short;
}
}
配置文件(新浪对接地址):
xinlang:
createApi: http://api.t.sina.com.cn/short_url/shorten.json?source=XXXXXXX
//source是微博开放平台申请应用时分配的AppKey