短链接 Java

简述:

短链接服务


实现:

1. 百度短链接服务

API: http://dwz.cn/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShortUrlUtil {
	private static Logger logger = LoggerFactory.getLogger(ShortUrlUtil.class);

	public static int TIMEOUT = 30 * 1000;
	public static String ENCODING = "UTF-8";

	/**
	 * JSON
	 * get value by key
	 * @param replyText
	 * @param key
	 * @return
	 */
	private static String getValueByKey_JSON(String replyText, String key){
		ObjectMapper mapper = new ObjectMapper();
		JsonNode node;
		String tinyUrl = null;
		try {
			node = mapper.readTree(replyText);
			tinyUrl = node.get(key).asText();	
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return tinyUrl;
	}

	

	/**
	 * 通过HttpConnection 获取返回的字符串
	 * @param connection
	 * @return
	 * @throws IOException
	 */
	private static String getResponseStr(HttpURLConnection connection) 
			throws IOException{
		StringBuffer result = new StringBuffer();
		int responseCode = connection.getResponseCode();

		if (responseCode == HttpURLConnection.HTTP_OK) {
			InputStream in = connection.getInputStream();
			BufferedReader reader = new BufferedReader(
				new InputStreamReader(in, ENCODING));
			String inputLine = "";
			while ((inputLine = reader.readLine()) != null) {
				result.append(inputLine);
			}
		}
		return String.valueOf(result);
	}

	
	/**‘
	 * 百度短链接接口  无法处理不知名网站,会安全识别报错
	 * @param args
	 */
	public static void main(String[] args) {  
		try{  
			URL url = new URL("http://dwz.cn/create.php");  
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();  
			//POST Request Define:   
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setConnectTimeout(TIMEOUT);
			connection.setRequestMethod("POST");
			String longUrl = "url=www.sina.com";
			
			connection.getOutputStream().write(longUrl.getBytes());
			connection.connect();  
			
			String responseStr = getResponseStr(connection);
			System.out.println("response string: " + responseStr);
			
			String tinyUrl = getValueByKey_JSON(responseStr, "tinyurl");
			System.out.println("tinyurl: " + tinyUrl);
		}catch(IOException e){  
			e.printStackTrace();
		}  
	}

}

输出:




2. 网易短链接

API:  http://126.am/apiManage.action

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ShortUrlUtil {
	private static Logger logger = LoggerFactory.getLogger(ShortUrlUtil.class);

	public static int TIMEOUT = 30 * 1000;
	public static String ENCODING = "UTF-8";

	public static void main(String[] args) {
		System.out.println(genShortUrl_WangYi(
			"http://192.168.1.199:8080/MyProj/verification?" +
				"userId=dddsewfasdfwefasdfasdf"));
	}
	
	/**
	 * 网易接口
	 * @param longUrl
	 * @return
	 */
	private static String USER_KEY = "asdfasdfasdfasdfasdfasffaf";
	public static String genShortUrl_WangYi(String longUrl) {  
		String shortUrl = "";
		try{  
			URL url = new URL("http://126.am/api!shorten.action?");  
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();  
			//POST Request Define:   
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setConnectTimeout(TIMEOUT);
			connection.setRequestMethod("POST");
			
			// POST params
			StringBuilder sbd = new StringBuilder();
			sbd.append("longUrl=").append(longUrl);
			sbd.append("&key=").append(USER_KEY);
			
			connection.getOutputStream().write(sbd.toString().getBytes());
			connection.connect();
 
			// response string
			String responseStr = getResponseStr(connection);
			
			// process response
			shortUrl = "http://" + getValueByKey_JSON(responseStr, "url");
			
		}catch(IOException e){  
			e.printStackTrace();
		}
		return shortUrl;
	}
	
	
	/**
	 * JSON
	 * get value by key
	 * @param replyText
	 * @param key
	 * @return
	 */
	private static String getValueByKey_JSON(String replyText, String key){
		ObjectMapper mapper = new ObjectMapper();
		JsonNode edd;
		String tinyUrl = null;
		try {
			edd = mapper.readTree(replyText);
			tinyUrl = edd.get(key).asText();	
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return tinyUrl;
	}


	/**
	 * 通过HttpConnection 获取返回的字符串
	 * @param connection
	 * @return
	 * @throws IOException
	 */
	private static String getResponseStr(HttpURLConnection connection) 
			throws IOException{
		StringBuffer responseStr = new StringBuffer();
		int responseCode = connection.getResponseCode();

		if (responseCode == HttpURLConnection.HTTP_OK) {
			InputStream in = connection.getInputStream();
			BufferedReader reader = new BufferedReader(
				new InputStreamReader(in, ENCODING));
			String inputLine = "";
			while ((inputLine = reader.readLine()) != null) {
				responseStr.append(inputLine);
			}
		}
		System.out.println(responseStr);
		return String.valueOf(responseStr);
	}

}



输出:












你可能感兴趣的:(Java)