springboot新浪微博短链接生成 redis缓存5分钟

ShortUrlUtil 

package com.ljzforum.platform.util;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLEncoder;

public class ShortUrlUtil {
	protected static Logger logger = LoggerFactory.getLogger(ShortUrlUtil.class);
	/**
	 * 获取短链接url
	 * */
	public static String getShortUrl(String url){
		if(StringUtils.isBlank(url)){
			return "";
		}
		try {
			url=URLEncoder.encode(url, "UTF-8");
			String requestUrl="http://api.t.sina.com.cn/short_url/shorten.json?source=2849184197&url_long="+url;
			HttpClient httpClient = new HttpClient();
			String data = httpClient.sendGet(requestUrl);
			if(StringUtils.isBlank(data)){
				data = httpClient.sendGet(requestUrl);
			}
			if(StringUtils.isBlank(data)){
				return "";
			}
			JSONArray jsonArray =JSONArray.fromObject(data);
			JSONObject jsonObject =(JSONObject) jsonArray.get(0);
			String shortUrl =  jsonObject.getString("url_short");
			if(shortUrl.equals("http://t.cn/")){
				return url;
			}else{
				return shortUrl;
			}
		} catch (Exception e) {
			logger.error("获取短链接url失败 url="+url);
		}
		return url;
	}
	public static void main(String[] args) {
		String url=getShortUrl("http://www.baidu.com");	
		System.out.println(url);
	}
}

redis缓存5分钟

    @Autowired
	private RedisTemplate redisTemplate;	
	/**
	 * 将链接缓存5分钟
	 */
	private String activityShortUrl(Integer id){
		String shortUrl = "";
		String urlKey = “PARTNER:SHORTURL:”+id;
		if (redisTemplate.hasKey(urlKey)) {
			shortUrl = (String) redisTemplate.opsForValue().get(urlKey);
			return shortUrl;
		}
		shortUrl = ShortUrlUtil.getShortUrl("你的长链接");
		if (StringUtils.isNotBlank(shortUrl) && !shortUrl.equals("http://t.cn/")) {
			redisTemplate.opsForValue().set(urlKey, shortUrl, 5, TimeUnit.MINUTES);
		}
		return shortUrl;
	}

httpClient

package com.ljzforum.platform.util;

import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.AbstractHttpMessage;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.*;

public class HttpClient {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	private static final int TIMEOUT_SECONDS = 120;
	private static final int POOL_SIZE = 120;
	private CloseableHttpClient httpclient = null;
	private String charst;

	public HttpClient() {
		httpclient = HttpClients.createDefault();
		this.charst = "UTF-8";

	}

	public HttpClient(String charst) {
		httpclient = HttpClients.createDefault();
		this.charst = charst;
	}

	/**
	 * 设置手机userAgent
	 */
	public HttpClient(String charst, boolean isMobileUserAgent) {
		if (isMobileUserAgent) {
			initMobileHttpClient();
		} else {
			httpclient = HttpClients.createDefault();
		}

		this.charst = charst;
	}

	public void initMobileHttpClient() {
		// Create global request configuration
		RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT_SECONDS * 1000)
				.setConnectTimeout(TIMEOUT_SECONDS * 1000).build();

		// Create an HttpClient with the given custom dependencies and
		// configuration.
		httpclient = HttpClients.custom().setMaxConnTotal(POOL_SIZE)
				.setMaxConnPerRoute(POOL_SIZE).setDefaultRequestConfig(defaultRequestConfig).build();

	}

	public CloseableHttpClient getHttpClient() {
		return httpclient;
	}

	public void close() {
		if (httpclient != null) {
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 发起http get请求
	 * @param url 请求的url
	 * */
	public String sendGet(String url) {
		return sendGet(url, null,null);
	}

	/**
	 * 发起http get 请求
	 * @param url
	 * @param headers
	 * @param params
	 * */
	public String sendGet(String url, Map<String ,String> params,Map<String,String> headers) {

		String html = null;
		RequestConfig.Builder builder = RequestConfig.custom();
		builder.setCircularRedirectsAllowed(true);// 设置是否区分调转
		RequestConfig config = builder.build();
		url = assembleURI(url, params);
		HttpGet httpget = new HttpGet(url);
		buildHeader(httpget, headers);
		httpget.setConfig(config);
		Integer httpResponseCode = 200;
		Integer requestStatus = 0;
		String result = "";
		try {
			CloseableHttpResponse response = httpclient.execute(httpget);
			httpResponseCode = response.getStatusLine().getStatusCode();
			Integer statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				html = EntityUtils.toString(entity, this.charst);
			}else{
				logger.error("http get请求异常 url=" + url+" statusCode ="+statusCode);
			}
			result = html;
		} catch (Exception e) {
			requestStatus = 1;
			result = ExceptionUtils.getStackTrace(e);
			logger.error("http get请求异常 url=" + url, e);
			return null;
		}
		return html;
	}

	/**
	 * 发起http get 请求
	 * @param url
	 * @param headers
	 * @param params
	 * */
	public JSONObject sendGetByJSON(String url, Map<String ,String> params,Map<String,String> headers) {
		String json = sendGet(url, params, headers);
		if(StringUtils.isNotBlank(json)){
			return JSONObject.fromObject(json);
		}
		return null;
	}

	/**
	 * 发起http get 请求
	 * @param url
	 * @param params
	 * */
	public JSONObject sendGetByJSON(String url, Map<String ,String> params) {
		String json = sendGet(url, params, null);
		if(StringUtils.isNotBlank(json)){
			return JSONObject.fromObject(json);
		}
		return null;
	}

	/**
	 * 发起http get请求
	 * @param url
	 * @param params 请求的参数
	 * */
	public String sendGet(String url, Map<String, String> params) {
		Set<String> keys = params.keySet();
		StringBuilder urlBuilder = new StringBuilder(url + "?");
		for (String key : keys) {
			urlBuilder.append(key).append("=").append(params.get(key)).append("&");
		}
		urlBuilder.delete(urlBuilder.length() - 1, urlBuilder.length());
		return this.sendGet(urlBuilder.toString());
	}

	/**
	 * 发起post请求
	 * @param url
	 * @param params
	 * */
	public String sendPost(String url, Map<String, String> params) {
		return sendPost(url, params,null);
	}

	/**
	 * 发起post请求返回字符串
	 * @param url
	 * @param params 请求的参数
	 * @param headers 请求的headers
	 * */
	public String sendPost(String url, Map<String, String> params,Map<String,String> headers) {
		String html = null;
		HttpPost post = new HttpPost(url);
		buildHeader(post, headers);
		Integer httpResponseCode = 200;
		Integer requestStatus = 0;
		String result = "";
		try {
			// 创建表单参数列表
			List<NameValuePair> qparams = new ArrayList<NameValuePair>();
			if (params != null) {
				Set<String> keys = params.keySet();
				for (String key : keys) {
					qparams.add(new BasicNameValuePair(key, params.get(key)));
				}
				// 设置编码
				post.setEntity(new UrlEncodedFormEntity(qparams, this.charst));
			}
			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				logger.debug("Response content length: " + entity.getContentLength());
			}

			html = EntityUtils.toString(entity, this.charst);
			result = html;
		} catch (Exception e) {
			requestStatus = 1;
			result = ExceptionUtils.getStackTrace(e);
			logger.error("sendPost异常: url=" + url, e);
			return null;
		}
		return html;
	}

	/**
	 * 发起post请求
	 * @param url
	 * @param params 请求的参数
	 * */
	public JSONObject sendPostByJSON(String url, Map<String, String> params){
		String json = sendPost(url, params);
		if(StringUtils.isNotBlank(json)){
			return JSONObject.fromObject(json);
		}
		return null;
	}

	/**
	 * 发起post请求
	 * @param url
	 * @param params 请求的参数
	 * @param header 请求的header参数
	 * */
	public JSONObject sendPostByJSON(String url, Map<String, String> params,Map<String,String> header){
		String json = sendPost(url, params,header);
		if(StringUtils.isNotBlank(json)){
			return JSONObject.fromObject(json);
		}
		return null;
	}

	/**
	 * post方法发送json数据
	 * @param url
	 * @param json
	 */
	public String sendPostJSON(String url, String json) {
		return sendPostJSON(url, json, null);
	}

	/**
	 * post方法发送json数据
	 * @param url
	 * @param json
	 */
	public JSONObject sendPostJSONByObj(String url, String json) {
		String jsonTmp = sendPostJSON(url, json, null);
		return JSONObject.fromObject(jsonTmp);
	}

	/**
	 * post方法发送json数据
	 * @param url
	 * @param json
	 * @param header 发送的header
	 */
	public String sendPostJSON(String url, String json, Map<String,String> header) {
		HttpPost post = new HttpPost(url);
		buildHeader(post,header);
		Integer httpResponseCode = 200;
		Integer requestStatus = 0;
		String result = null;
		try {
			StringEntity stringentity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);// 解决中文乱码问题
			post.setEntity(stringentity);
			HttpResponse response = httpclient.execute(post);
			httpResponseCode = response.getStatusLine().getStatusCode();
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				logger.debug("Response content length: " + entity.getContentLength());
			}
			result = EntityUtils.toString(entity, this.charst);

		} catch (Exception e) {
			requestStatus = 1;
			result = ExceptionUtils.getStackTrace(e);
			logger.error("sendPostJson异常:", e);
			return null;
		}
		return result;
	}

	/**
	 * put方法发送json数据
	 */
	public String sendPutByJSON(String url, String json) {
		HttpPut httpPut = new HttpPut(url);
		Integer httpResponseCode = 200;
		Integer requestStatus = 0;
		String result = null;
		Map<String,String> params = new HashMap<String,String>();
		params.put("json",json);
		try {
			StringEntity stringentity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);// 解决中文乱码问题
			httpPut.setEntity(stringentity);
			HttpResponse response = httpclient.execute(httpPut);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				logger.debug("Response content length: " + entity.getContentLength());
			}
			result = EntityUtils.toString(entity, this.charst);

		} catch (Exception e) {
			requestStatus = 1;
			result = ExceptionUtils.getStackTrace(e);
			logger.error("sendPutByJson异常:", e);
			return null;
		}
		return result;
	}

	/**
	 * delete方法发送json数据
	 */
	public String sendDeleteByUrl(String url) {
		Integer httpResponseCode = 200;
		Integer requestStatus = 0;
		String result = null;
		HttpDelete httpDelete = new HttpDelete(url);
		try {

			HttpResponse response = httpclient.execute(httpDelete);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				logger.debug("Response content length: " + entity.getContentLength());
			}
			result = EntityUtils.toString(entity, this.charst);

		} catch (Exception e) {
			requestStatus = 1;
			result = ExceptionUtils.getStackTrace(e);
			logger.error("sendDeleteByJson异常:", e);
			return null;
		}
		return result;
	}

	/**
	 * 获取请求http数据流,比如下载图片
	 * */
	public InputStream sendGetInputStream(String url) {
		if (url.startsWith("https")) {
			httpclient = SSLClient.createSSLClientDefault();
		}
		RequestConfig.Builder builder = RequestConfig.custom();
		builder.setCircularRedirectsAllowed(true);// 设置是否区分调转
		RequestConfig config = builder.build();
		HttpRequestBase httpGet = new HttpGet(url);
		httpGet.setConfig(config);
		try {

			CloseableHttpResponse response = httpclient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				return entity.getContent();
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取http字节流失败  url=" + url, e);
			return null;
		}
		return null;

	}

	/**
	 * 获取请求http数据流,比如下载图片
	 * @param url
	 * @param json
	 * */
	public InputStream sendPostInputStream(String url, String json) {
		HttpPost post = new HttpPost(url);
		try {
			StringEntity stringentity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);// 解决中文乱码问题
			post.setEntity(stringentity);
			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			InputStream iStream = entity.getContent();
			Charset charset = ContentType.get(entity).getCharset();
			if (entity.getContentType().getValue().startsWith("application/json")) {
				int i = (int) entity.getContentLength();
				if (i < 0) {
					i = 4096;
				}
				final Reader reader = new InputStreamReader(iStream, charset);
				final CharArrayBuffer buffer = new CharArrayBuffer(i);
				final char[] tmp = new char[1024];
				int l;
				while ((l = reader.read(tmp)) != -1) {
					buffer.append(tmp, 0, l);
				}
			}
			return iStream;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取http字节流失败  url=" + url, e);
			return null;
		} finally {
			try {
				post.abort();
				httpclient.close();
			} catch (Exception e2) {
				logger.error("httpclient关闭异常>: url=" + url, e2);
			}
		}
	}

	/**
	 *进行post请求
	 * @param content
	 * @param url
	 * */
	public String sendPost(String url, String content) {
		HttpPost post = new HttpPost(url);
		Integer httpResponseCode = 200;
		Integer requestStatus = 0;
		String result = null;
		try {
			StringEntity stringentity = new StringEntity(content.toString(), ContentType.APPLICATION_JSON);// 解决中文乱码问题
			post.setEntity(stringentity);
			HttpResponse response = httpclient.execute(post);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				logger.debug("Response content length: " + entity.getContentLength());
			}
			return EntityUtils.toString(entity, this.charst);
		} catch (Exception e) {
			requestStatus = 1;
			result = ExceptionUtils.getStackTrace(e);
			e.printStackTrace();
			logger.error("获取http字节流失败  url=" + url, e);
			return null;
		}
	}

	/**
	 * 发送http请求带有headers
	 * @param url 请求的url
	 * @param params 请求的数据
	 * @param headers 请求的header
	 */
	public String sendGetHeaders(String url, Map<String, String> params, Map<String, String> headers) {
		if(params != null && params.size() > 0){
			Set<String> keys = params.keySet();
			StringBuilder urlBuilder = new StringBuilder(url + "?");
			for (String key : keys) {
				urlBuilder.append(key).append("=").append(params.get(key)).append("&");
			}
			url = urlBuilder.delete(urlBuilder.length() - 1, urlBuilder.length()).toString();
		}

		String html = null;
		RequestConfig.Builder builder = RequestConfig.custom();
		builder.setCircularRedirectsAllowed(true);// 设置是否区分调转
		RequestConfig config = builder.build();
		HttpGet httpget = new HttpGet(url);
		httpget.setConfig(config);
		try {
			for (Map.Entry<String, String> e : headers.entrySet()) {
				httpget.addHeader(e.getKey(), e.getValue());
			}
			CloseableHttpResponse response = httpclient.execute(httpget);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				html = EntityUtils.toString(entity, this.charst);
			} else {
				logger.error("http请求失败=" + response.getStatusLine().getStatusCode() + "url=" + url);
			}
		} catch (Exception e) {
			logger.error("http get请求异常", e);
			return null;
		} finally {
			httpget.abort();
			try {
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return html;
	}

	/**
	 * 用于上传微信素材
	 * */
	public String mediaUploadGraphic(String wxurl,String access_token, String mediaType, File media) {
		String result = null;
		HttpURLConnection con = null;
		try {
			// 拼装请求地址
			String uploadMediaUrl = String.format(wxurl, access_token, mediaType);
			URL url = new URL(uploadMediaUrl);
			// File file = new File("mediaFileUrl");
			if (!media.exists() || !media.isFile()) {
				//System.out.println("上传的文件不存在");
			}

			con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("POST"); // 以Post方式提交表单,默认get方式
			con.setDoInput(true);
			con.setDoOutput(true);
			con.setUseCaches(false); // post方式不能使用缓存
			// 设置请求头信息
			con.setRequestProperty("Connection", "Keep-Alive");
			con.setRequestProperty("Charset", "UTF-8");
			// 设置边界
			String BOUNDARY = "----------" + System.currentTimeMillis();
			con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

			// 请求正文信息
			// 第一部分:
			StringBuilder sb = new StringBuilder();
			sb.append("--"); // 必须多两道线
			sb.append(BOUNDARY);
			sb.append("\r\n");
			String filename = media.getName();
			sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + filename + "\" \r\n");
			sb.append("Content-Type:application/octet-stream\r\n\r\n");
			byte[] head = sb.toString().getBytes("utf-8");

			// 获得输出流
			OutputStream out = new DataOutputStream(con.getOutputStream());
			// 输出表头
			out.write(head);
			// 文件正文部分
			// 把文件已流文件的方式 推入到url中
			DataInputStream in = new DataInputStream(new FileInputStream(media));
			int bytes = 0;
			byte[] bufferOut = new byte[1024];
			while ((bytes = in.read(bufferOut)) != -1) {
				out.write(bufferOut, 0, bytes);
			}
			in.close();

			// 结尾部分
			byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("utf-8");// 定义最后数据分隔线
			out.write(foot);
			out.flush();
			out.close();

			StringBuffer buffer = new StringBuffer();
			BufferedReader reader = null;
			// 定义BufferedReader输入流来读取URL的响应
			reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			if (result == null) {
				result = buffer.toString();
			}
		} catch (IOException e) {
			logger.error("发送POST请求出现异常!" + e);
			e.printStackTrace();
		} finally {
			if(con != null){
				con.disconnect();
			}
		}

		return result;
	}

	protected static void buildHeader(AbstractHttpMessage httpMessage, Map<String, String> headers) {
		if ((headers == null) || (headers.isEmpty())) {
			return;
		}
		for (String key : headers.keySet())
			httpMessage.setHeader(new BasicHeader(key, headers.get(key).toString()));
	}

	protected static String assembleURI(String uri, Map<String, String> params) {
		if ((params == null) || (params.isEmpty())) {
			return uri;
		}
		List parameters = new ArrayList();
		for (String key : params.keySet()) {
			Object object = params.get(key);
			if (object != null)
			{
				parameters.add(new BasicNameValuePair(key, object.toString()));
			}
		}
		String paramPath = URLEncodedUtils.format(parameters, "UTF-8");
		if (-1 == uri.indexOf("?"))
			uri = uri + "?" + paramPath;
		else {
			uri = uri + "&" + paramPath;
		}
		return uri;
	}

	public static void main(String[] args) {

	}

}

参考文章:
https://www.sojson.com/blog/330.html
https://blog.csdn.net/Kindle_code/article/details/77098007

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值