Java FacebookのOGPキャッシュクリア

はじめに

というかHttpClientの使い方、といったところですが・・。 事前に以下のライブラリを用意します。

今回のサンプルは以下のjarがあれば動作します。

  • httpclient-4.5.1.jar
  • httpcore-4.4.4.jar

実装例

サンプルでは、動作確認しやすいようにmainメソッドで実行できるようにしてあります。 結果だけを確認したい場合は、この記事の一番下のリンク先で使えるようにしてありますのでご覧ください。

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;

/**
 *
 * @author tool-taro.com
 */
public class ScrapeOgp {

    public static void main(String[] args) throws UnsupportedEncodingException, IOException {

        //クリアしたいURL
        String url = "http://.../";
        //ユーザエージェント
        String userAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0";
        //タイムアウト(ミリ秒)
        int timeout = 10000;

        //クリアリクエスト処理
        ByteArrayOutputStream bout = new ByteArrayOutputStream();

        List<Header> headers = new ArrayList<>();
        if (userAgent != null) {
            headers.add(new BasicHeader("User-Agent", userAgent));
        }
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout).setCircularRedirectsAllowed(true).setRedirectsEnabled(true).build();
        CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setDefaultHeaders(headers).build();

        HttpPost httpPost = new HttpPost("https://graph.facebook.com/");
        List<NameValuePair> requestParams = new ArrayList<>();
        requestParams.add(new BasicNameValuePair("id", url));
        requestParams.add(new BasicNameValuePair("scrape", "true"));
        httpPost.setEntity(new UrlEncodedFormEntity(requestParams));
        CloseableHttpResponse response = null;

        BufferedInputStream in = null;

        try {
            response = httpclient.execute(httpPost);
            in = new BufferedInputStream(response.getEntity().getContent());
            byte[] buf = new byte[1024];
            int length;
            while (true) {
                length = in.read(buf);
                if (length == -1) {
                    break;
                }
                bout.write(buf, 0, length);
            }
        }
        finally {
            if (in != null) {
                try {
                    in.close();
                }
                catch (Exception e) {
                }
            }
            if (response != null) {
                try {
                    response.close();
                }
                catch (Exception e) {
                }
            }
        }

        //標準出力
        System.out.format("リクエスト結果=%1$s", new String(bout.toByteArray(), "UTF-8"));
    }
}

動作確認

$ javac ScrapeOgp.java
$ java ScrapeOgp
$ リクエスト結果={
   "url": ...(省略)

なお、リクエストを送信しても、Facebook側の状況次第では受け付けられない・反映されないケースがあります。ご注意ください。

環境

上記の実装をベースにWebツールも公開しています。 FacebookのOGPキャッシュクリア|Web便利ツール@ツールタロウ