百度自动提交URL

以前一直觉得在某某论坛才发表了帖子,居然百度直接收录了。
原来有这个功能(百度站长主动推送),以前一直没有得到这个权限,所以一直也没做过这东西,今天发现居然有了这个权限了,立马就来写了:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
 
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
 
/**
 * 百度自动提交URL
 */
public class BaiduPoster {
 
    private static final String POST_URL = "http://data.zz.baidu.com/urls?site=www.acgist.com&token=token";
     
    public static void main(String[] args) {
        System.out.println(post("http://www.acgist.com/artic/225.html", "http://www.acgist.com/artic/217.html"));
    }
     
    /**
     * 提交连接
     * @param urls 连接集合
     */
    public static String post(String ... urls) {
        if(ArrayUtils.isEmpty(urls))
            return null;
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("User-Agent", "curl/7.12.1"); // 可不填写
        post.addHeader("Host", "data.zz.baidu.com"); // 可不填写
        post.addHeader("Content-Type", "text/plain");
        post.addHeader("Connection", "close"); // 不是长连接
        try {
            String urlsStr = StringUtils.join(urls, "\n"); // 拼接字符串
            post.setEntity(new ByteArrayEntity(urlsStr.getBytes()));
            HttpResponse response= client.execute(post); // 执行请求
            // 读取返回内容
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            String tmp = null;
            StringBuffer message = new StringBuffer();
            while((tmp = br.readLine()) != null)
                message.append(tmp);
            return message.toString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            post.abort();
            client.getConnectionManager().shutdown();
        }
        return null;
    }
     
}

上面例子中用到了HTTPClient和Apache的一些工具包。HTTPClient的版本是4.2+的。