packagecom.test.salesforce.restful;importjava.io.IOException;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;importorg.apache.http.Header;importorg.apache.http.HttpResponse;importorg.apache.http.HttpStatus;importorg.apache.http.ParseException;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.HttpClient;importorg.apache.http.client.methods.HttpDelete;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.client.methods.HttpPost;importorg.apache.http.entity.StringEntity;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.impl.client.HttpClientBuilder;importorg.apache.http.message.BasicHeader;importorg.apache.http.params.DefaultedHttpParams;importorg.apache.http.params.HttpParams;importorg.apache.http.util.EntityUtils;importorg.json.JSONArray;importorg.json.JSONException;importorg.json.JSONObject;importorg.json.JSONTokener;public classTestSalesforceRestful {static final String USERNAME = "weizhen.zhao@pactera.com";static final String PASSWORD = "zwz87865918vYoQKmkHZ3CHvlWxktmXybWi";static final String LOGINURL = "https://login.salesforce.com";static final String GRANTSERVIVE = "/services/oauth2/token?grant_type=password";static final String CLIENTID = "3MVG9YDQS5WtC11rl9X0l.9UJjmHTftDEUlhQz8SsxqKUk5iRxSgSp2aeKxM1NHJBkzp.VJqIT56XXPnLk5oi";static final String CLIENTSECRET = "9102086465628528777";private static String REST_ENDPOINT = "/services/apexrest";private staticString baseUri;private staticHeader oauthHeader;private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");public static voidmain(String[] args) {//测试restful 创建一个merchandise//createMerchandise("testSalesforceRestfulApi", "2000", "20001");//测试restful 查询一个List结果集
/*List list = getMerchandiseByName("testSalesforceRestfulApi");
for (Merchandise item : list) {
System.out.print(item.getName() + "\t");
System.out.print(item.getPrice() + "\t");
System.out.println(item.getQuantity() + "\t");
}*/
//删除一个Merchandise//deleteMerchandise("testSalesforceRestfulApi");
}public static voiddeleteMerchandise(String name) {if(isAccessable()) {
HttpClient client=HttpClientBuilder.create().build();
String url= baseUri + "/deleteMerchandise/" +name;
HttpDelete delete= newHttpDelete(url);
delete.addHeader(oauthHeader);
delete.addHeader(prettyPrintHeader);
HttpResponse response= null;try{
response=client.execute(delete);int statusCode =response.getStatusLine().getStatusCode();if (statusCode ==HttpStatus.SC_OK) {
System.out.println("Deleted the goods successfully.");
}else{
System.out.println("goods delete NOT successful. Status code is " +statusCode);
}
delete.releaseConnection();
}catch(IOException e) {
e.printStackTrace();
}
}
}/*** distinguish whether can access sfdc or not
*
*@return
*/
private static booleanisAccessable() {
HttpClient httpClient=HttpClientBuilder.create().build();//Assemble the login request URL
String loginURL = LOGINURL + GRANTSERVIVE + "&client_id=" + CLIENTID + "&client_secret=" +CLIENTSECRET+ "&username=" + USERNAME + "&password=" +PASSWORD;//Login requests must be POSTs
HttpPost httpPost = newHttpPost(loginURL);
HttpResponse response= null;try{
response=httpClient.execute(httpPost);
}catch(ClientProtocolException cpException) {
cpException.printStackTrace();
}catch(IOException ioException) {
ioException.printStackTrace();
}//verify response is HTTP OK
final int statusCode =response.getStatusLine().getStatusCode();if (statusCode !=HttpStatus.SC_OK) {
System.out.println("Error authenticating to Force.com:" +statusCode);return false;
}
String getResult= null;try{
getResult=EntityUtils.toString(response.getEntity());
}catch (ParseException |IOException e) {
e.printStackTrace();
}
JSONObject jsonObject= null;
String loginAccessToken= null;
String loginInstanceUri= null;try{
jsonObject= (JSONObject) newJSONTokener(getResult).nextValue();
loginAccessToken= jsonObject.getString("access_token");
loginInstanceUri= jsonObject.getString("instance_url");
}catch(JSONException jsonException) {
jsonException.printStackTrace();
}
baseUri= loginInstanceUri + REST_ENDPOINT + "/Merchandise";
oauthHeader= new BasicHeader("Authorization", "Bearer " +loginAccessToken);
System.out.println("oauthHeader1:" +oauthHeader);
System.out.println(response.getStatusLine());
System.out.println("Successful login");
System.out.println("instance URL:" +loginInstanceUri);
System.out.println("access token/sessing ID:" +loginAccessToken);
System.out.println("baseUri:" +baseUri);return true;
}/*** httpGet請求RESTful
*
*@paramname
*@return
*/
public static ListgetMerchandiseByName(String name) {if(isAccessable()) {
String uri= baseUri + "/getMerchandiseByName?name=" +name;
System.out.println(uri);
HttpClient client=HttpClientBuilder.create().build();
HttpGet get= newHttpGet(uri);
get.setHeader(oauthHeader);
get.setHeader(prettyPrintHeader);try{
HttpResponse response=client.execute(get);int statusCode =response.getStatusLine().getStatusCode();if (statusCode ==HttpStatus.SC_OK) {
List merchandiseList = new ArrayList();
String response_string=EntityUtils.toString(response.getEntity());
System.out.println("response_string:" +response_string);
JSONArray jsonArray= newJSONArray(response_string);
JSONObject jsonObject= null;for (int i = 0; i < jsonArray.length(); i++) {
jsonObject=jsonArray.getJSONObject(i);
Merchandise item= newMerchandise();if (jsonObject != null) {
item.setName(jsonObject.getString("Name"));
item.setPrice(jsonObject.getDouble("Price__c"));
item.setQuantity(jsonObject.getInt("Quantity__c"));
}
merchandiseList.add(item);
}
get.releaseConnection();returnmerchandiseList;
}else{
get.releaseConnection();return null;
}
}catch(JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}catch(NullPointerException npe) {
npe.printStackTrace();
}
}return null;
}/*** httpPost請求 call restful api to create a merchandise return merchandise Id
*
*@paramname
*@paramprice
*@paramquantity*/
public static voidcreateMerchandise(String name, String price, String quantity) {try{if(isAccessable()) {
String uri= baseUri + "/insertMerchandise";
System.out.println(uri);
JSONObject merchandise= newJSONObject();
merchandise.put("name", name);
merchandise.put("price", price);
merchandise.put("quantity", quantity);
System.out.println("JSON for merchandises record to be insert:\n" +merchandise.toString());//Construct the objects needed for the request
HttpClient httpClient =HttpClientBuilder.create().build();
;
System.out.println("oauthHeader" +oauthHeader);
HttpPost httpPost= newHttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
httpPost.addHeader("encoding", "UTF-8");//The message we are going to post
StringEntity body = new StringEntity(merchandise.toString(1));
System.out.println(merchandise.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body);//Make the request
HttpResponse response =httpClient.execute(httpPost);
System.out.println("response: " +response.toString());//Process the results
int statusCode =response.getStatusLine().getStatusCode();
System.out.println("status code: " +statusCode);if (statusCode ==HttpStatus.SC_OK) {
String response_String=EntityUtils.toString(response.getEntity());if (response_String != null) {
System.out.println("New Merchandise id from response:" +response_String);
}
}else{
System.out.println("Insertion unsuccessful.Status code returned is" +statusCode);
}
httpPost.releaseConnection();
}
}catch(JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}catch(NullPointerException npe) {
npe.printStackTrace();
}
}
}