Gradle Project Learning & Httpasyncclient Learning & Countdownlatch Learning

Source: Internet
Author: User

Installed IntelliJ, is installed Gradle.

Create a new Gradle project. Then the following page will check the above two items:

Use Auto-import and create directories for empty content roots automatically these two options on the hook.

Create a new project for each directory and file:

    • Support files for. Gradle,gradle, no Tube
    • . Idea,intellij the relevant documents of idea, do not care
    • Build, building the build, and storing the class and jar packages generated in the project build
    • Gradle, a gradle packaging procedures, seemingly directly with gradle not too good, we have to pack a layer, this actually we do not have to tube
    • SRC, where we write the code, needless to say.
    • Build.gradle,gradle's build configuration, that's what we're interested in, equivalent to Maven's Pom.xml
    • Project name. project file for Iml,intellij idea
    • Gradlew, a Gradle wrapper run script, for *nix
    • Gradlew.bat, a Gradle wrapper run script, for Windows
    • Settings.gradle, configuration?

Build.gradle configuration:

Group ' com.async.client' 1.0-snapshot' java 'sourcecompatibility = 1.8Repositories {    mavenlocal ()    mavencentral ()}Tasks.withtype (javacompile) {    = "UTF-8"  }dependencies {    ' org.apache.httpcomponents ', Name: ' Httpasyncclient ', Version: ' 4.1.1    ' JUnit ', Name: ' JUnit ', Version: ' 4.11 '}

After adding mavenlocal (), Gradle will try to get the jar package from the local MAVEN cache first, which will be faster.

Dependencies is a variety of dependency packages, compile represents compile-time dependencies, and Testcompile represents the compilation dependency when performing unit tests.

Task.withtype () This paragraph means using UTF-8 encoding, in order to avoid the problem of compiling, we all use UTF-8 encoding.

Gradle Project Window Right-click the project name, "Synchronizing ...".

The foreign maven is too slow, the Gradle inside is configured as follows:

repositories {    //MAVEN library    def CN = "http://maven.aliyun.com/nexus/content/groups/public/"    def abroad = "http://central.maven.org/maven2/"    //download jar from URL if not found, find     maven {        URL cn        in Artifacturls Artifacturls Abroad    }} 

Then found two repositories repeated, so the original, the final file content as follows:

Group ' Com.async' 1.0-snapshot ' java '= 1.8Repositories {    //  Maven Library    def CN = "http://maven.aliyun.com/nexus/content/groups/public/"    = "http +// central.maven.org/maven2/"    //  download jar from URL if not found, find maven in Artifacturls     {        URL cn        Artifacturls abroad    }}dependencies {    ' org.apache.httpcomponents ', Name: ' Httpasyncclient ', version: ' 4.1.1    ' JUnit ', Name: ' JUnit ', Version: ' 4.11 '}

Use the menu view-> Tools View, Gradle to bring up the Gradle configuration interface.

Click on the button above to reload the dependency. With the domestic repository is indeed much faster.

Now that the package is ready to download, start writing the program.

Among them, Countdownlatch, a synchronous helper class, allows one or more threads to wait until a set of operations that are performed in another thread is completed.

Note also that the usage of httpasyncclients is similar to the asynchronous invocation inside JS.

 PackageCom.async;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.client.methods.HttpGet;ImportOrg.apache.http.concurrent.FutureCallback;Importorg.apache.http.impl.nio.client.CloseableHttpAsyncClient;Importorg.apache.http.impl.nio.client.HttpAsyncClients;Importorg.apache.http.util.EntityUtils;Importjava.io.IOException;ImportJava.util.concurrent.CountDownLatch;/*** Created by Baidu on 16/11/26.*/ Public classasyncclient { Public Static voidMain (string[] argv) {closeablehttpasyncclient httpasyncclient=Httpasyncclients.createdefault ();        Httpasyncclient.start (); FinalCountdownlatch latch =NewCountdownlatch (1); FinalHttpGet HttpGet =NewHttpGet ("https://www.alipay.com/"); System.out.println ("Caller thread ID:" +Thread.CurrentThread (). GetId ()); Httpasyncclient.execute (HttpGet,NewFuturecallback() {@Override Public voidcompleted (HttpResponse result) {Latch.countdown (); System.out.println ("Callback thread ID:" +Thread.CurrentThread (). GetId ()); System.out.println (Httpget.getrequestline ()+ "+" +result.getstatusline ()); String content=NULL; Try{content= Entityutils.tostring (Result.getentity (), "UTF-8"); System.out.println ("Response content is:" +content); } Catch(IOException e) {e.printstacktrace (); }} @Override Public voidfailed (Exception ex) {Latch.countdown (); System.out.println ("Callback thread ID:" +Thread.CurrentThread (). GetId ()); System.out.println (Httpget.getrequestline ()+ "+" +ex); } @Override Public voidcancelled () {latch.countdown (); System.out.println ("Callback thread ID:" +Thread.CurrentThread (). GetId ()); System.out.println (Httpget.getrequestline ()+ "+" + "cancelled");        }        }); Try{latch.await (); } Catch(interruptedexception e) {e.printstacktrace (); }        Try{httpasyncclient.close (); } Catch(IOException e) {e.printstacktrace (); }    }}

Run to get results:

Caller thread id:1GET https://www.alipay.com/HTTP/1.1->HTTP/1.1 OK  <!--fd:83:homeproxy/home/startup.vm:start--><!--fd:83:homeproxy/home/startup.vm:634: startup.schema:startup-Header page Description: START--><! DOCTYPE html> ...

A method such as "Getjson ()" can be implemented with a little encapsulation.

Perhaps you also notice, this httpclient and synchronous version of the same, directly support HTTPS, but if the site's certificate is self-signed , default or not, the solution of course, but the code is a bit troublesome, I think it is better to buy a certificate directly to come simple, If the website is your tube.

Gradle Project Learning & Httpasyncclient Learning & Countdownlatch Learning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.