调用第三方接口生成短链接(一)

      短链接,通俗来说,就是将长的URL网址,通过程序计算等方式,转换为简短的网址字符串。有时也称短网址(Short URL)。

  这里第三方接口使用nowapi ,  注册网址:https://www.nowapi.com。通过注册得到appkey和sign。 

  接口文档地址:https://www.nowapi.com/api/shorturl.set

  Java jar包:httpclient-4.5.jar,httpclient-cache-4.5.jar,httpclient-win-4.5.jar,httpcore-4.4.1.jar,httpmime-4.5.jar

  下载地址:http://download.csdn.net/detail/litter_fisher/9923346。

  测试代码如下:

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;

public class TestNowapi {

     public static void main(String args[]) throws Exception {         
      String longUrl = "http://www.baidu.com";  
      String SIGN = "4a9331cccbc3ff30dde78d0b51fb4239";    
      String APPKEY = "26835";
//        URL u=new URL("http://api.k780.com/?app=shorturl.set&url=需要缩短的网址(需要urlencode)&appkey={APPKEY}&sign={SIGN}&format=json");
      URL u=new URL("http://api.k780.com/?app=shorturl.set&url="+longUrl+"&appkey="+APPKEY+"&sign="+SIGN+"&format=json");
            
          InputStream in=u.openStream();
          ByteArrayOutputStream out=new ByteArrayOutputStream();
          try {
              byte buf[]=new byte[1024];
              int read = 0;
              while ((read = in.read(buf)) > 0) {
                  out.write(buf, 0, read);
              }
          }  finally {
              if (in != null) {
                  in.close();
            }
        }
        byte b[]=out.toByteArray( );
        
        System.out.println(new String(b,"utf-8"));
  }

}

  

 

 

  

 

posted @ 2017-07-28 15:33  loytime  阅读(1381)  评论(0编辑  收藏  举报