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/