Searching...
Sunday, 23 June 2013

Restful Java client using Apache HttpClient example

04:24

Example

Add below dependency in your maven pom.xml

    <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4.1</version>
        </dependency>

Test class

package com.vinod.vinod_rest_examples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class ApacheHttpRestClient {

    public static void main(String[] args) throws ClientProtocolException, IOException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet request = new HttpGet("xxxxxx--service url");
        HttpResponse response = httpClient.execute(request);
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = br.readLine()) != null) {
            System.out.println("Output: " + line);
        }
    }
}

0 comments: