java使用google网址缩短

package com.dorole.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class Googl
{
	private static String googUrl = "https://www.googleapis.com/urlshortener/v1/url";

	public static String shorten(String longUrl)
	{
		String shortUrl = "";
		try
		{
			URLConnection conn = new URL(googUrl).openConnection();
			conn.setDoOutput(true);
			conn.setRequestProperty("Content-Type", "application/json");
			OutputStreamWriter osw = new OutputStreamWriter(
					conn.getOutputStream());
			osw.write("{\"longUrl\":\"" + longUrl + "\"}");
			osw.flush();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String line;
			while ((line = br.readLine()) != null)
			{
				if (line.indexOf("id") > -1)
				{
					shortUrl = line.substring(8, line.length() - 2);
					break;
				}
			}
			osw.close();
			br.close();
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return shortUrl;
	}

	public static void main(String[] args)
	{
		String url = Googl.shorten("http://dorole.com");
		System.out.println(url);
	}
}

需要的地方调用Googl.shorten(), 参考:link, 引自:link

本文链接地址:https://dorole.com/406/

来自:Dorole's Blog

发布者

Steve

编程/摄影

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

:wink: :-| :-x :twisted: :) 8-O :( :roll: :-P :oops: :-o :mrgreen: :lol: :idea: :-D :evil: :cry: 8) :arrow: :-? :?: :!: