Total Pageviews

2018/10/13

[Java] How to write a client program to call restful service

Scenario


How-To
Client code:
package test.albert.rest.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RestClient {

    private final String GET_URL = "http://localhost:8080/api/greeting/get/sayHi?name=Albert";
    private final String POST_URL = "http://localhost:8080/api/greeting/post/sayHi";

    public static void main(String[] args) throws IOException {
        RestClient client = new RestClient();
        client.doGetRequest();
        client.doPostRequest();
    }

    public void doGetRequest() throws IOException {
        HttpClient client = new HttpClient();
        GetMethod getMethod = new GetMethod(GET_URL);
        try {
            int statusCode = client.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                String error = "do Get Request failed: " + getMethod.getStatusLine();
                throw new RuntimeException(error);
            }

            String responseBodyStr = getMethod.getResponseBodyAsString();
            log.debug("[doGetRequest] responseBodyStr = " + responseBodyStr);
        } catch (IOException e) {
            throw e;
        } finally {
            getMethod.releaseConnection();
        }
    }

    public void doPostRequest() throws JsonProcessingException, UnsupportedEncodingException {
        String greetingJson = createJSON();
        StringRequestEntity requestEntity = new StringRequestEntity(greetingJson, "application/json", "UTF-8");

        HttpClient client = new HttpClient();

        PostMethod postMethod = new PostMethod(POST_URL);
        postMethod.setRequestEntity(requestEntity);

        try {
            int statusCode = client.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                String error = "do Post Request failed: " + postMethod.getStatusLine();
                throw new RuntimeException(error);
            }
            
            String responseStr = postMethod.getResponseBodyAsString();
            log.debug("[doPostRequest] responseStr = " + responseStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }

    }

    private String createJSON() throws JsonProcessingException {
        Greeting greeting = new Greeting("Hello, Mandy", null);
        return new ObjectMapper().writeValueAsString(greeting);
    }

    @AllArgsConstructor
    @NoArgsConstructor
    @Data
    @ToString
    private static class Greeting {
        private String content;

        @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss.SSS", timezone = "GMT+8")
        private Date datetime;
    }

}

Add dependency into pom.xml
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
  
 <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.3</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.3</version>
        </dependency>






No comments: