Apache HttpClient example with Maven [JAVA]

Posted By: Matpal Media - 11:59 AM
Step one.
<dependencies>
 <dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.2</version>
</dependency>
  </dependencies>

Update pom.xml with following entry



Step two

Execute following code


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

public class Main 
{

    public static void main(String[] args) 
    {
        try
        {
        String url = "http://wikipedia.org";

        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);


        request.addHeader("User-Agent", "USER_AGENT");
        HttpResponse response = client.execute(request);

            System.out.println("Response Code : "
                + response.getStatusLine().getStatusCode());
       }
       catch(Exception e)
       {
          System.out.println(e); 
       }
    }
}

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.