Skip to content

Instantly share code, notes, and snippets.

@jmertic
Last active August 4, 2017 04:45
Show Gist options
  • Save jmertic/5844627 to your computer and use it in GitHub Desktop.
Save jmertic/5844627 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();
}
}
}
@smalyshev
Copy link

Not sure why you expect code 201 from Sugar on oauth2/token. It returns 200 AFAIK.

@jmertic
Copy link
Author

jmertic commented Jun 24, 2013

@mmarum-sugarcrm please do run an give me any feedback on changes. Don't have a Java env so I have nowhere to run it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment