java 通过第三方接口生成短链接
本文介绍通过http://suo.im/api.php第三方接口生成短链接。
package com.my.controller.api;
import com.my.utils.HTTPUtils;
import com.my.utils.StringUtils;
import com.my.web.Message;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 生成短连接
*/
@Controller
@RequestMapping("/api/shortUrl")
public class ShortUrlController {
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public Message getShortUrl(String url){
if(null == url){
return Message.error("参数为空");
}
List<NameValuePair> pairs = new ArrayList<>();
//设置接口返回格式
pairs.add(new BasicNameValuePair("format", "json"));
pairs.add(new BasicNameValuePair("url", url));
Map<String, String> rst;
try {
rst = HTTPUtils.getGetResp("http://suo.im/api.php", pairs, "UTF-8");
} catch (Exception e) {
return Message.error("请求错误");
}
JSONObject json = JSONObject.fromObject(rst.get("responseBody"));
if(StringUtils.isEmpty(json.getString("err"))){
String shortUrl = json.getString("url");
if(StringUtils.isEmpty(shortUrl)){
return Message.error("请求错误");
}else{
return Message.success(shortUrl);
}
}else{
return Message.error(json.getString("err"));
}
}
}
相关HTTPUtils类
package com.my.utils;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.*;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apach