How do I set indexed property value of a bean?

In this example we show how to set the value of an indexed property. In the code below we modified the value of an array type. We’ll change the second colors of MyBean‘s colors property.

We do it in the same way as we are using the PropertyUtils.setSimpleProperty method. For indexed property we use the PropertyUtils.setIndexedProperty method and passes four arguments, they are the instance of bean to be manipulated, the indexed property name, the index to be changes and finally the new value.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.MyBean;

import java.util.Arrays;

public class PropertySetIndexedExample {
    public static void main(String[] args) {
        String[] colors = new String[]{"red", "green", "blue"};

        MyBean myBean = new MyBean();
        myBean.setColors(colors);
        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));

        try {
            PropertyUtils.setIndexedProperty(myBean, "colors", 1, "orange");
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Colors = " + Arrays.toString(myBean.getColors()));
    }
}
package org.kodejava.commons.beanutils.support;

public class MyBean {
    private String[] colors;

    public void setColors(String[] colors) {
        this.colors = colors;
    }

    public String[] getColors() {
        return colors;
    }
}

The output of this code is:

Colors = [red, green, blue]
Colors = [red, orange, blue]

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

How do I set property value of a bean?

The Commons BeanUtils component provides a class called PropertyUtils that supplies method for manipulating a bean such as our Track class below. For this demo we use a Track class that have a property called id, title and duration.

To set the value of a bean we can use the PropertyUtils.setProperty() method. This method ask for the bean instance whose property value to be set, the property name and the value.

package org.kodejava.commons.beanutils;

import org.apache.commons.beanutils.PropertyUtils;
import org.kodejava.commons.beanutils.support.Track;

public class PropertySetExample {
    public static void main(String[] args) {
        Track track = new Track();
        try {
            PropertyUtils.setProperty(track, "id", 10L);
            PropertyUtils.setProperty(track, "title", "Hey Jude");
            PropertyUtils.setProperty(track, "duration", 180);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Track = " + track);
    }
}
package org.kodejava.commons.beanutils.support;

public class Track {
    private Long id;
    private String title;
    private Integer duration;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getDuration() {
        return duration;
    }

    public void setDuration(Integer duration) {
        this.duration = duration;
    }

    @Override
    public String toString() {
        return "Track{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", duration=" + duration +
                '}';
    }
}

Some exceptions could be thrown by this method, so we need to handle the IllegalAccessException, InvocationAccessException and NoSuchMethodException. To make the code simple we will just catch it as java.lang.Exception.

These exceptions could happen if we don’t have access to the property, or the bean’s accessor throws an exception or if the method we tried to manipulate doesn’t exist.

Maven Dependencies

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>

Maven Central

How do I add query string to HttpMethod object?

To send query string information in HTTP GET command you either using passing a simple string or an array of NameValuePair object into the HttpMethod‘s setQueryString() method. We also need to encode the parameter values before passing it to the method.

package org.kodejava.commons.httpclient;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.IOException;

public class SendingQueryParameter {
    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("http://localhost:8080/hello.jsp");

        try {
            // Set query string information for accessing the page using a
            // simple string information.
            method.setQueryString(URIUtil.encodeQuery("catid=10&page=1"));
            client.executeMethod(method);

            // Other cleaner alternative is to use the NameValuePair object to
            // define the parameters for an HTTP GET method.
            NameValuePair param1 = new NameValuePair("catid", URIUtil.encodeQuery("20"));
            NameValuePair param2 = new NameValuePair("page", URIUtil.encodeQuery("2"));
            NameValuePair[] params = new NameValuePair[]{param1, param2};
            method.setQueryString(params);
            client.executeMethod(method);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

Maven Central

How do I set a proxy for HttpClient?

In this example you will see how to configure proxy when using the Apache Commons HttpClient library.

package org.kodejava.commons.httpclient;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.IOException;

public class HttpGetProxy {
    private static final String PROXY_HOST = "proxy.host.com";
    private static final int PROXY_PORT = 8080;

    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("https://kodejava.org");

        HostConfiguration config = client.getHostConfiguration();
        config.setProxy(PROXY_HOST, PROXY_PORT);

        String username = "guest";
        String password = "s3cr3t";
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);

        client.getState().setProxyCredentials(authScope, credentials);

        try {
            client.executeMethod(method);

            if (method.getStatusCode() == HttpStatus.SC_OK) {
                String response = method.getResponseBodyAsString();
                System.out.println("Response = " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

Maven Central

How do I perform HTTP GET method?

Below is an example using Commons HttpClient library to retrieve information from a website using HTTP GET method. The response will be returned as stream by the HttpMethod.getResponseBodyAsStream() method. If you want something simple you can get the response as string by using the HttpMethod.getResponseBodyAsString() method.

package org.kodejava.commons.httpclient;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class HttpGetDemo {
    public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("https://kodejava.org");

        try {
            client.executeMethod(method);

            if (method.getStatusCode() == HttpStatus.SC_OK) {
                InputStream is = method.getResponseBodyAsStream();

                if (is != null) {
                    Writer writer = new StringWriter();
                    char[] buffer = new char[1024];
                    try {
                        Reader reader = new BufferedReader(new InputStreamReader(is,
                                StandardCharsets.UTF_8));
                        int length;
                        while ((length = reader.read(buffer)) != -1) {
                            writer.write(buffer, 0, length);
                        }
                    } finally {
                        is.close();
                    }
                    System.out.println("Response = " + writer);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>

Maven Central