Skip to content

Instantly share code, notes, and snippets.

@ronbeltran
Forked from jmertic/gist:5844627
Last active August 29, 2015 14:27
Show Gist options
  • Save ronbeltran/7fef58801bb1f173a92a to your computer and use it in GitHub Desktop.
Save ronbeltran/7fef58801bb1f173a92a to your computer and use it in GitHub Desktop.
Sample Java code using Jersey and JSONObject for connecting to the new RESTful SugarCRM REST API in 6.7 and later.
package com.sugarcrm.client;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import net.sf.json.JSONObject;
public class JerseyClientPost {
public static void main(String[] args) {
try {
Client client = Client.create();
// specify the REST web service to interact with
String baseurl = "<<instanceurl>>/rest/v10";
WebResource webResource = client.resource(baseurl + "/oauth2/token");
JSONObject jsonInput = new JSONObject()
.element( "grant_type", "password" )
.element( "username", "<<username>>" )
.element( "password", "<<password>>" )
.element( "client_id", "sugar" );
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, jsonInput.toString());
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
JSONObject jsonOutput = (JSONObject) JSONSerializer.toJSON( response.getEntity(String.class) );
if ( jsonOutput.has("error") ) {
throw new RuntimeException("Failed : " + jsonOutput.getString("error_message"));
}
String token = jsonOutput.getString("access_token");
System.out.println("Success! OAuth token is " + token);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment