java调用百度API生成短链接(二) (转)

import net.sf.json.*;

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 org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import java.util.*;

/**

 * 生成短网址并返回

 * @author: lyh

 * @date: 2015年10月27日下午23:58:54

 */

public class duanlianjieTest {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**

     * 生成端连接信息

     *

     * @author: lyh

     * @date: 2015年10月27日下午23:58:54

     */

    public static void 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 = new DefaultHttpClient().execute(httpost);

            String jsonStr = EntityUtils

                .toString(response.getEntity(), "utf-8");

            JSONObject jsonObj = JSONObject.fromObject(jsonStr.replace("\\",""));

            System.out.println("短链接"+jsonObj.get("tinyurl"));

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    /**

     * 测试生成端连接

     * @param args

     * @author: lyh

     * @date: 2015年10月27日下午23:58:54

     */

    public static void main(String []args){

        generateShortUrl("http://write.blog.csdn.net/postlist");

    }

}

猜你喜欢

转载自frank1998819.iteye.com/blog/2367631