天天看點

自動送出站點最新文章到百度

個人站點最新文章送出到百度(java實作)

如果個人擁有自己的站點,并且想把最近更新的檔案送出到百度,參考  http://zhanzhang.baidu.com/linksubmit/index 。

官方沒有給出java 示例,這裡寫了一個,測試通過。

import java.io.IOException;

import java.util.List;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.ContentType;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

public static String pushUrl(String url)
    {
        int timeout = 30;
        RequestConfig config = RequestConfig.custom()
                  .setConnectTimeout(timeout * 1000)
                  .setConnectionRequestTimeout(timeout * 1000)
                  .setSocketTimeout(timeout * 1000).build();
        
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
        
        HttpPost hp = new HttpPost("接口調用位址, 見: http://zhanzhang.baidu.com/linksubmit/index");
        hp.setHeader("Host", "data.zz.baidu.com");
        hp.setHeader("User-Agent", "curl/7.12.1");
        hp.setHeader("Content-Type", "text/plain");
    
      
        HttpResponse httpresponse;
        HttpEntity entity = null;
        
        
        try
        {
            StringEntity jsonEntity = new StringEntity(url, ContentType.TEXT_PLAIN);
            hp.setEntity(jsonEntity);

            httpresponse = httpClient.execute(hp);
            entity = httpresponse.getEntity();
            String body = EntityUtils.toString(entity);
            
            return body;
            
            
        
        } catch (ClientProtocolException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } finally {
            if(entity != null)
                try
                {
                    entity.getContent().close();
                } catch (IllegalStateException e)
                {
                    e.printStackTrace();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            
            hp.releaseConnection();
        }
        
        return null;
    }      

1、 用到 httpclient 包。apache 站點可下載下傳。

2、 StringEntity jsonEntity = new StringEntity(url, ContentType.TEXT_PLAIN);  

      hp.setEntity(jsonEntity);

     實際是 http post Json 送出方法

c#