您的位置:首页 > 编程语言 > Java开发

JAVA实现网址缩短

2012-10-30 21:45 197 查看
腾讯微博发出去的URL网址能够自动缩短。JAVA能否实现网址缩短?答案是可以的。

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://http://blog.csdn.net/powmxypow");

System.out.println(url);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: