0

Unable to get access token. here my code given below

public class MainActivity extends Activity {

private static final String query = "SELECT Name, Idfrom Account";
private static final String clientId = "";
private static final String clientSecret = "";
private static final String redirectUri = "";
private static final String environment = "http://login.salesforce.com";
private static String tokenUrl = null;
private static final String username = "";
private static final String password = "";
private static String accessToken = null;
private static String instanceUrl = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    // Creating HTTP client
    HttpClient httpClient = new DefaultHttpClient();

    tokenUrl = environment + "/services/oauth2/token";

    HttpPost httpPost = new HttpPost(tokenUrl);

    // Building post parameters
    // key and value pair
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("grant_type", "password"));
    nameValuePair.add(new BasicNameValuePair("client_id", clientId));
    nameValuePair.add(new BasicNameValuePair("client_secret", clientSecret));
    nameValuePair.add(new BasicNameValuePair("redirect_uri", redirectUri));
    nameValuePair.add(new BasicNameValuePair("username", username));
    nameValuePair.add(new BasicNameValuePair("password", password));

    // Url Encoding the POST parameters
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {
        // writing error to Log
        e.printStackTrace();
    }

    // Making HTTP Request
    try {
        HttpResponse response = httpClient.execute(httpPost);

        // writing response to log
        Log.v("Http Response: >>>>>", "Http Response: >>>>>0000   "
                + response);
    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();

    }
}

}

in response i'm getting org.apache.http.message.BasicHttpResponse@917d22c

  • You can use Salesforce REST api in your app to get salesforce data. Salesforce provides a REST api and you can refer following link for more information. developer.salesforce.com/docs/atlas.en-us.api_rest.meta/… – coderdecoder May 20 '18 at 15:50
  • yes, I have used Rest API and I get the Salesforce data. but my requirement is I am not wanted login screen. when the app is started it will first ask for credentials. there is any way without login I get salesforce data or through code login is possible. – Harish May 20 '18 at 16:14
  • Grab an access token using the connected app and use it to make rest calls. developer.salesforce.com/docs/atlas.en-us.api_rest.meta/… – coderdecoder May 20 '18 at 16:27
  • I am getting error while request for token Caused by: java.lang.RuntimeException: Could not retrieve access token for user: I also post my code – Harish May 21 '18 at 6:20
  • Thanks, ankit.sehgal i get salesforce records using access tokn – Harish May 22 '18 at 6:58
0

For Access Salesforce records in Android Native App without login credentials, you first need to grab access token from salesforce.

To get access token you can follow this link. https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_oauth.htm

After grabbing a token you need to make REST calls to get Salesforce Records.

package com.example.admin.myapplication;

public class MainActivity extends Activity {

// The connection data
private static final String query = "SELECT Name, Id from Account";
private static final String clientId = "Your salesforce consumer Key";
private static final String clientSecret = "Secret Key";
// THis is meaningless in our context
private static final String redirectUri = "Redirect URI";
//private static final String environment = "https://harishgakhar40-dev-ed.my.salesforce.com";
private static final String environment = "https://login.salesforce.com";
private static String tokenUrl = null;
private static final String username = "salesforce Username";
private static final String password = "salesforce password + security token";
private static String accessToken = null;
private static String instanceUrl = null;
private ArrayAdapter<String> listAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create list adapter
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
    ((ListView) findViewById(R.id.contacts_list)).setAdapter(listAdapter);
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    // Creating HTTP client
    HttpClient httpClient = new DefaultHttpClient();

    tokenUrl = environment + "/services/oauth2/token?grant_type=password&client_id=" + clientId + "&client_secret=" + clientSecret + "&username=" + username + "&password=" + password;
    HttpPost httpPost = new HttpPost(tokenUrl);

    // Building post parameters
    // key and value pair
    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);

    nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e){
        // writing error to Log
        e.printStackTrace();
    }
    JSONTokener tokener;
    String accessToken,instanceURL;
    JSONArray finalResult;
    // Making HTTP Request
    try {

        HttpResponse response = httpClient.execute(httpPost);
        int code = response.getStatusLine().getStatusCode();

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String json = reader.readLine();
        JSONObject jObj = new JSONObject(json);
        accessToken = jObj.getString("access_token");
        instanceURL = jObj.getString("instance_url");
       getAccountData(accessToken, instanceURL);

    } catch (Exception e) {

        e.getMessage();

    }
}


public  void getAccountData(String access_token, String instance_url) {

    DefaultHttpClient client = new DefaultHttpClient();
    String url = instance_url + "/services/data/v20.0/query/?q=";
    String soqlQuery = "Select Id, Name, BillingStreet, BillingCity, BillingState From Account ";

    try
    {
        url += URLEncoder.encode(soqlQuery, "UTF-8");
    }
    catch(UnsupportedEncodingException e){}

    HttpGet getRequest = new HttpGet(url);
    getRequest.addHeader("Authorization", "OAuth " + access_token);

    try {
        HttpResponse response = client.execute(getRequest);

        String result = EntityUtils.toString(response.getEntity());

        JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
        JSONArray records = object.getJSONArray("records");

        listAdapter.clear();
        for (int i=0;i<records.length();i++) {


            JSONObject record = (JSONObject) records.get(i);
            String accountName = record.getString("Name");
            Log.v("accountName---- ","accountName ---- "+accountName);
            listAdapter.add(accountName);

        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.