对于java程序员来说,自己运维的百度熊掌号当然得使用java的方式去每天推送文章了。目前,百度推出了百度熊掌号服务。旨在更好的为站长服务。那么百度熊掌号如何通过推送API接口实现自动文章推送呢?
第一步:注册
注册百度熊掌号,获取推送链接appid以及token,注册地址如下:https://ziyuan.baidu.com/xzh/home/index?appid=1605577821816999
第二步:程序代码,用到的jar包如下:
用java代码实现的推送,代码如下:import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
public class BaiduUtils {
private final static Log log = LogFactory.getLog(BaiduUtils.class);
public static final int ORIGINAL_TYPE = 1;
public static void doHttpRequest(String url,String postUrls) {
DefaultHttpClient httpclient = new DefaultHttpClient();
org.apache.http.params.HttpParams params = httpclient.getParams();
org.apache.http.params.HttpConnectionParams.setConnectionTimeout(params, 5000);
org.apache.http.params.HttpConnectionParams.setSoTimeout(params, 1000 * 60 * 10);
DefaultHttpRequestRetryHandler dhr = new DefaultHttpRequestRetryHandler(3, true);
HttpContext localContext = new BasicHttpContext();
httpclient.setHttpRequestRetryHandler(dhr);
org.apache.http.client.methods.HttpPost post = new org.apache.http.client.methods.HttpPost();
try {
post.setEntity(new ByteArrayEntity(postUrls.getBytes()));
post.setURI(URI.create(url));
HttpResponse response = null;
response = httpclient.execute(post, localContext);
System.out.println("Http执行结果" + EntityUtils.toString(response.getEntity(), "utf-8"));
} catch (Exception e) {
System.out.println("Http执行异常");
}
}
public static void doHttpRequest(String url,List urls) {
if (urls != null && urls.size() > 0) {
doHttpRequest(url,StringUtils.join(urls, "\n"));
}
}
public static void post(List urls,Integer type) {
if (type != null && type == BaiduUtils.ORIGINAL_TYPE) {
BaiduUtils.doHttpRequest("http://data.zz.baidu.com/urls?appid=你的appid&token=你的网站token&type=realtime", urls);
}
}
public static void post(List urls) {
BaiduUtils.doHttpRequest("http://data.zz.baidu.com/urls?appid=你的appid&token=你的网站token&type=realtime", urls);
}
public static void main(String[] args) {
List arrayList = new ArrayList();
arrayList.add("http://www.itxm.cn/post/15615.html");
arrayList.add("http://www.itxm.cn/post/15616.html");
BaiduUtils.post(arrayList);
}
}