Java - JSON and REST

From XennisWiki
(Redirected from HttpComponents)
Jump to: navigation, search

This article shows a Java example of how to post and get data via a REST API using JSON.

Example

Apache HTTP client

org/example/sampleapi/ApacheHttpClient.java

<gist file="ApacheHttpClient.java">9263251</gist>

Sample API

org/example/sampleapi/SampleAPI.java

package org.example.sampleapi;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class SampleAPI {

	/**
	 * URL of the API server.
	 */
	public static final String API_URL = "http://localhost:8000/api/v1/";

	/**
	 * API access token.
	 */
	private static final String ACCESS_TOKEN = "f0d56e559c";

	
	/**
	 * Get a list with all locations.
	 * 
	 * @return List with locations
	 */
	public List<Location> getLocations() {

		List<Location> locationList = new ArrayList<Location>();
		try {
			String result = ApacheHttpClient.httpGet(API_URL + Location.ressourceName + "/", "OAuth " + ACCESS_TOKEN);

			JSONArray ar = new JSONObject(result).getJSONArray("objects");
			Gson gsonBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
			for(int i=0;i<ar.length();i++){
				Location ink = gsonBuilder.fromJson(ar.get(i).toString(), Location.class);
				locationList.add(ink);
			}		
		} catch (RuntimeException | JSONException e) {
			System.err.println(e.getClass().getName() + " " + e.getMessage());
		}
		
		return locationList;
	}
	
	public boolean postLocation(Location location) {
		try {
			String stringEntity = new Gson().toJson(location);
			return ApacheHttpClient.httpPost(API_URL + Location.ressourceName + "/", "OAuth " + ACCESS_TOKEN, stringEntity);
		} catch (RuntimeException e) {
			System.err.println(e.getClass().getName() + " " + e.getMessage());
		}

		return false;
	}
}

org/example/sampleapi/Location.java

package org.example.sampleapi;

public class Location {

	public static final String ressourceName = "location";

	private float latitude;
	private float longitude;
	private float altitude;
	private int user_id;

	public Location(float latitude, float longitude, float altitude, int user_id) {
		this.latitude = latitude;
		this.longitude = longitude;
		this.altitude = altitude;
		this.user_id = user_id;
	}
	
	public float getLatitude() {
		return latitude;
	}

	public void setLatitude(float latitude) {
		this.latitude = latitude;
	}

	public float getLongitude() {
		return longitude;
	}

	public void setLongitude(float longitude) {
		this.longitude = longitude;
	}

	public float getAltitude() {
		return altitude;
	}

	public void setAltitude(float altitude) {
		this.altitude = altitude;
	}

	public int getUser_id() {
		return user_id;
	}

	public void setUser_id(int user_id) {
		this.user_id = user_id;
	}

	@Override
	public String toString() {
		return "Location [latitude=" + latitude + ", longitude=" + longitude
				+ ", altitude=" + altitude + ", user_id=" + user_id + "]";
	}	


}

Test

src/Main.java

import java.util.List;

import org.example.sampleapi.Location;
import org.example.sampleapi.SampleAPI;

public class Main {

	public static void main(String[] args) {
		SampleAPI sampleAPI = new SampleAPI();
		
		System.out.println("----------------- Get locations -----------------");
		List<Location> locationList = sampleAPI.getLocations();
		for (Location l : locationList) {
			System.out.println(l);
		}

		System.out.println("----------------- Post location -----------------");
		int sampleUser_id = 3;
		Location sampleLocation = new Location(55, 12, 110, sampleUser_id);
		boolean postResult = sampleAPI.postLocation(sampleLocation);
		if (postResult) {
			System.out.println("post successful: " + sampleLocation);
		} else {
			System.out.println("post failed: " + sampleLocation);			
		}
	}
}

Simple example

Parse JSON to Object using GSON

Parse JSON string to Java Object

String response = "{\n" +
                "    \"success\": true,\n" +
                "    \"hostname\": \"exampe.org\"\n" +
                "}";
Gson gson = new GsonBuilder()
                .setFieldNamingStrategy( new UnderscoreFieldNamingStrategy() )
                .create();
ExampleResponse exampleResponse = gson.fromJson( response, ExampleResponse.class );
// exampleResponse.isSuccess()
// exampleResponse.getHostname()

Special strategy to translate Java bean fiel names _myField to JSON field names myField

static class UnderscoreFieldNamingStrategy implements FieldNamingStrategy {

    @Override
    public String translateName( final Field field ) {
        String fieldName = FieldNamingPolicy.IDENTITY.translateName( field );
        if ( fieldName.startsWith( Strings.UNDERSCORE ) ) {
            fieldName = fieldName.substring( 1 );
        }
        return fieldName;
    }
}

RecaptchaValidateResponse.java bean

class RecaptchaValidateResponse {

    private boolean _success;
    private String _hostname;

    @SerializedName( "status-success" )
    public boolean isSuccess() {
        return success;
    }

    public String getHostname() {
        return hostname;
    }
}

HTTP post using HttpClient

General post method

private void postRequest( final String url, final List<NameValuePair> params ) {
    final CloseableHttpClient client = HttpClients.createDefault();
    final HttpPost httpPost = new HttpPost( url );
    httpPost.setEntity( new UrlEncodedFormEntity( params ) );

    try {
        final CloseableHttpResponse response = client.execute( httpPost );
        // Get status code and content
        System.out.println( response.getStatusLine().getStatusCode() );
        String responseString = EntityUtils.toString( response.getEntity() );
        System.out.println( responseString );
        // Close connection
        EntityUtils.consume( response.getEntity() );
    } catch ( IOException e ) {
        e.printStackTrace();
    }
}
postRequest( "http://example.org/api/test", params );

See also