java调用百度短网址api

来源:互联网 发布:加工中心的编程分为 编辑:程序博客网 时间:2024/04/27 09:59

  1. 怎样调用百度短网址API?
    1. 生成短网址

    请求:向dwz.cn/create.php发送post请求,发送数据包括url=长网址

    返回:json格式的数据

    1. status!=0 出错,查看err_msg获得错误信息(UTF-8编码)
    2. 成功,返回生成的短网址 tinyurl字段
    1. 自定义短网址

    请求:向dwz.cn/create.php发送post请求,发送数据包括url=长网址&alias=自定义网址

    返回:json格式的数据

    1. Status!=0 出错,查看err_msg获得错误信息(UTF-8编码)
    2. 成功,返回生成的短网址 tinyurl字段
    1. 显示原网址

    请求:向dwz.cn/query.php发送post请求,发送数据包括tinyurl=查询的短地址

    返回:json格式的数据

    1. status!=0 出错,查看err_msg获得错误信息(UTF-8编码)
    2. 成功,返回原网址 longurl字段

    示例程序:

    生成短网址
    <?php
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,"http://dwz.cn/create.php");
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $data=array('url'=>'http://www.baidu.com/');
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    $strRes=curl_exec($ch);
    curl_close($ch);
    $arrResponse=json_decode($strRes,true);
    if($arrResponse['status']==0)
    {
    /**错误处理*/
    echo iconv('UTF-8','GBK',$arrResponse['err_msg'])."\n";
    }
    /** tinyurl */
    echo $arrResponse['tinyurl']."\n";
    ?>其他接口使用如上

示例:java调用百度短网址api

import java.util.ArrayList;import java.util.List;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;/** * 生成短网址并返回 * @author: Jerri  * @date: 2014年3月22日下午9:58:54 */public class GenerateShortUrlUtil {public static DefaultHttpClient httpclient;static {httpclient = new DefaultHttpClient();httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient); // 接受任何证书的浏览器客户端}/** * 生成端连接信息 *  * @author: Jerri  * @date: 2014年3月22日下午5:31:15 */public static String  generateShortUrl(String url) {try {HttpPost httpost = new HttpPost("http://dwz.cn/create.php");List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("url", url)); // 用户名称httpost.setEntity(new UrlEncodedFormEntity(params,  "utf-8"));HttpResponse response = httpclient.execute(httpost);String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");System.out.println(jsonStr);JSONObject object = JSON.parseObject(jsonStr);System.out.println(object.getString("tinyurl"));return object.getString("tinyurl");} catch (Exception e) {e.printStackTrace();return "Error";}}/** * 测试生成端连接 * @param args * @author: Jerri  * @date: 2014年3月22日下午5:34:05 */public static void main(String []args){generateShortUrl("http://help.baidu.com/index");}}


1 0