本文介绍通过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.apache.http.util.EntityUtils;
/**
* Utils - HTTP GET
*/
public final class HTTPUtils {
/** UTF-8字符集编码 */
public static final String UTF_8 = "UTF-8";
private HTTPUtils() {
}
/**
* 获取响应信息
*
* @param url 请求地址
* @param httpParameters 请求参数
* @return 响应数据
*/
public static Map<String, String> getGetResp(String url, List<NameValuePair> httpParameters) throws Exception {
Map<String, String> map = new HashMap<String, String>();
CloseableHttpClient httpClient = null;
ByteArrayOutputStream exceptionOutputStream = null;
CloseableHttpResponse httpResponse = null;
PrintStream exceptionPrintStream = null;
try {
HttpGet httpGet = new HttpGet(url);
httpClient = HttpClients.createDefault();
String sendstr = "";
if (httpParameters != null && !httpParameters.isEmpty()) {
sendstr = EntityUtils.toString(new UrlEncodedFormEntity(httpParameters, UTF_8));
httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + sendstr));
} else {
httpGet.setURI(new URI(httpGet.getURI().toString()));
}
map.put("requestUrl", url);
map.put("requestMethod", httpGet.getMethod());
map.put("requestTime", DateUtils.formatTime(new Date()));
map.put("requestHeaders", getHeaders(httpGet.getAllHeaders()));
map.put("requestBody", getBody(httpParameters).toString());
httpResponse = httpClient.execute(httpGet);
int responseStatus = httpResponse.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(httpResponse.getEntity(), "GB2312"/*UTF_8*/);
map.put("responseStatus", String.valueOf(responseStatus));
map.put("responseBody", responseBody);
map.put("responseTime", DateUtils.formatTime(new Date()));
map.put("responseHeaders", getHeaders(httpResponse.getAllHeaders()));
} catch (Exception e) {
e.printStackTrace();
// 获取异常
exceptionPrintStream = new PrintStream(exceptionOutputStream);
exceptionOutputStream = new ByteArrayOutputStream();
map.put("exception", new String(exceptionOutputStream.toByteArray()));
e.printStackTrace(exceptionPrintStream);
} finally {
IOUtils.closeQuietly(httpResponse);
IOUtils.closeQuietly(httpClient);
IOUtils.closeQuietly(exceptionPrintStream);
IOUtils.closeQuietly(exceptionOutputStream);
}
return map;
}
/**
* 获取响应信息
*
* @param url 请求地址
* @param httpParameters 请求参数
* @return 响应数据
*/
public static Map<String, String> getGetResp(String url, List<NameValuePair> httpParameters,String charset) throws Exception {
Map<String, String> map = new HashMap<String, String>();
CloseableHttpClient httpClient = null;
ByteArrayOutputStream exceptionOutputStream = null;
CloseableHttpResponse httpResponse = null;
PrintStream exceptionPrintStream = null;
try {
HttpGet httpGet = new HttpGet(url);
httpClient = HttpClients.createDefault();
String sendstr = "";
if (httpParameters != null && !httpParameters.isEmpty()) {
sendstr = EntityUtils.toString(new UrlEncodedFormEntity(httpParameters, UTF_8));
httpGet.setURI(new URI(httpGet.getURI().toString() + "?" + sendstr));
} else {
httpGet.setURI(new URI(httpGet.getURI().toString()));
}
map.put("requestUrl", url);
map.put("requestMethod", httpGet.getMethod());
map.put("requestTime", DateUtils.formatTime(new Date()));
map.put("requestHeaders", getHeaders(httpGet.getAllHeaders()));
map.put("requestBody", getBody(httpParameters).toString());
httpResponse = httpClient.execute(httpGet);
int responseStatus = httpResponse.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(httpResponse.getEntity(), charset);
map.put("responseStatus", String.valueOf(responseStatus));
map.put("responseBody", responseBody);
map.put("responseTime", DateUtils.formatTime(new Date()));
map.put("responseHeaders", getHeaders(httpResponse.getAllHeaders()));
} catch (Exception e) {
e.printStackTrace();
// 获取异常
exceptionPrintStream = new PrintStream(exceptionOutputStream);
exceptionOutputStream = new ByteArrayOutputStream();
map.put("exception", new String(exceptionOutputStream.toByteArray()));
e.printStackTrace(exceptionPrintStream);
} finally {
IOUtils.closeQuietly(httpResponse);
IOUtils.closeQuietly(httpClient);
IOUtils.closeQuietly(exceptionPrintStream);
IOUtils.closeQuietly(exceptionOutputStream);
}
return map;
}
/**
* 获取响应信息
*
* @param url 请求地址
* @param json 请求参数
* @return 响应数据
*/
public static Map<String, String> getPostResp(String url, String json) throws Exception {
Map<String, String> map = new HashMap<String, String>();
// String response = null;
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
ByteArrayOutputStream exceptionOutputStream = null;
PrintStream exceptionPrintStream = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/json");
map.put("requestParam", json);
StringEntity httpEntity = new StringEntity(json, Charset.forName("utf-8"));
httpPost.setEntity(httpEntity);
httpResponse = httpClient.execute(httpPost);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(httpResponse.getEntity(), UTF_8);
map.put("statusCode", String.valueOf(statusCode));
map.put("info", responseBody);
} catch (Exception e) {
e.printStackTrace();
// 获取异常
exceptionPrintStream = new PrintStream(exceptionOutputStream);
exceptionOutputStream = new ByteArrayOutputStream();
map.put("info", new String(exceptionOutputStream.toByteArray()));
e.printStackTrace(exceptionPrintStream);
} finally {
IOUtils.closeQuietly(httpResponse);
IOUtils.closeQuietly(httpClient);
IOUtils.closeQuietly(exceptionPrintStream);
IOUtils.closeQuietly(exceptionOutputStream);
}
return map;
}
/**
* 获取响应信息
*
* @param url 请求地址
* @param httpParameters 请求参数
* @return 响应数据
*/
public static Map<String, String> getPostByFormResp(String url, List<NameValuePair> httpParameters) throws Exception {
Map<String, String> map = new HashMap<String, String>();
CloseableHttpClient httpClient = null;
CloseableHttpResponse httpResponse = null;
ByteArrayOutputStream exceptionOutputStream = null;
PrintStream exceptionPrintStream = null;
try {
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.setEntity(new UrlEncodedFormEntity(httpParameters,Charset.forName("utf-8")));
map.put("requestUrl", url);
map.put("requestMethod", httpPost.getMethod());
map.put("requestTime", DateUtils.formatTime(new Date()));
map.put("requestHeaders", getHeaders(httpPost.getAllHeaders()));
map.put("requestBody", getBody(httpParameters).toString());
httpResponse = httpClient.execute(httpPost);
int responseStatus = httpResponse.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(httpResponse.getEntity(), UTF_8);
map.put("responseStatus", String.valueOf(responseStatus));
map.put("responseBody", responseBody);
map.put("responseTime", DateUtils.formatTime(new Date()));
map.put("responseHeaders", getHeaders(httpResponse.getAllHeaders()));
} catch (Exception e) {
// 获取异常
exceptionOutputStream = new ByteArrayOutputStream();
exceptionPrintStream = new PrintStream(exceptionOutputStream);
map.put("exception", new String(exceptionOutputStream.toByteArray()));
e.printStackTrace(exceptionPrintStream);
} finally {
IOUtils.closeQuietly(httpResponse);
IOUtils.closeQuietly(httpClient);
IOUtils.closeQuietly(exceptionPrintStream);
IOUtils.closeQuietly(exceptionOutputStream);
}
return map;
}
/**
* 获取通信头部信息
*
* @param headers 数组
* @return 响应数据
*/
private static String getHeaders(Header... headers){
StringBuffer headerstr = new StringBuffer();
if (headers != null && headers.length >0){
for (Header header: headers){
headerstr.append(header.getName());
headerstr.append("→");
headerstr.append(header.getValue());
headerstr.append("|");
}
}
return headerstr.toString();
}
/**
* 获取通信参数信息
*
* @param httpParameters 参数列表
* @return 响应数据
*/
private static String getBody(List<NameValuePair> httpParameters){
if (httpParameters == null || httpParameters.isEmpty()){
return "";
}
StringBuffer requestBody=new StringBuffer();
Iterator it= httpParameters.iterator();
while(it.hasNext()) {
NameValuePair parameter = (NameValuePair)it.next();
String encodedName = parameter.getName();
String encodedValue = parameter.getValue();
if(requestBody.length() > 0) {
requestBody.append("&");
}
requestBody.append(encodedName);
if(encodedValue != null) {
requestBody.append("=");
requestBody.append(encodedValue);
}
}
return requestBody.toString();
}
}