Client Execute Direct using apache http - Java Network

Java examples for Network:apache http

Description

Client Execute Direct using apache http

Demo Code


import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class ClientExecuteDirect {

    public static void main(String[] args) {
        try (final CloseableHttpClient hc = HttpClients.createDefault();) {
            HttpHost target = new HttpHost("www.apache.org", 80, "http");
            HttpGet req = new HttpGet("/");
            System.out.println("executing reqeust " + target);

            HttpResponse res = hc.execute(target, req);
            System.out.println("------------------------------------");
            System.out.println(res.getStatusLine());
            Header[] headers = res.getAllHeaders();
            for (Header header : headers) {
                System.out.println(header);
            }//from   w  ww. ja v  a2s.  c om
            System.out.println("------------------------------------");

            HttpEntity entity = res.getEntity();
            if (entity != null) {
                System.out.println(EntityUtils.toString(entity));
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Related Tutorials