Post cURL Java

Today we will see how to make a command Post cURL Java, this procedure is valid on any Java platform (Windows or Linux). I made this post after implementing the cache cleaning for re-share on social (Facebook, Linkedin & Twitter) so in my app the user could manually change the icon that will appear in the company post.

For Facebook you must rerun via cURL the sharing debugger located at this url: developers.facebook.com/tools/debug/sharing/ in http post mode.

We will see that functionality implemented in two ways: with standard commands of the Java Platform or by JAR Library.

Standard Java

        URL url = new URL("https://graph.facebook.com");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
 
        writer.write("id=<YOUR-SHARE-URL>&scrape=true");
        writer.flush();
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        writer.close();
        reader.close();

AsyncHttpClient
To use this library you must be entered in pom.xml this dependency.

        <dependency>
            <groupId>com.ning</groupId>
            <artifactId>async-http-client</artifactId>
            <version>1.9.36</version>
        </dependency>

While then in the Java class you will have the following instructions.

        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        AsyncHttpClient.BoundRequestBuilder r = asyncHttpClient.preparePost("https://graph.facebook.com");
        r.addFormParam("id", "<YOUR-SHARE-URL>");
        r.addFormParam("scrape", "true");
        Future<Response> f = r.execute();
        Response res = f.get();
        System.out.println(res.getStatusCode() + ": " + res.getStatusText());
        System.out.println(res.getResponseBody());
        asyncHttpClient.closeAsynchronously();

I prefer the first strategy if it is a simple cURL like that of Facebook. In contrast to cURL solutions may be the most complex Runtime.exec command (command) for Java, or even the use of AsyncHttpClient library can be a valuable solution.

Post cURL Java ultima modidfica: 2016-10-08T10:35:08+02:00 da Gianluca Di Vincenzo