function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
neelam mooreneelam moore 

SOAP session ID on a REST api call

Hi,

I wanted to test the REST connectivity from a stand alone java code. Since the couldnt find an example online i modified the current rest demo available in the salesforce api to use SOAP login instead of oAuth login. I read somewhere in this forum that we can use the soap login to obtain the user sessionId which can be used to make rest api.  So I tried to modify the rest demo code as shown below . I was able to connect successfully to salesforc test environmet and get the session id. I m i using this session id in place of the the accesstoken to set the get method's request header. But now i m getting a connection time out error .  I  did set the proxy host and port correctly so I doubt it can be a proxy issue as i was also able to connecti using the SOAP Enterprise connection. I m not sure i m doing this the right way can someone please guide me or point out any mistakes i made ? 

Code :

package com.cww.salesforce.restapi;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpHost;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.Header;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.message.BasicHeader;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
public class DemoREST extends HttpServlet {
 private static final long serialVersionUID = 1L;
 public DemoREST(){
   
 }
 static EnterpriseConnection connection;
 static String sessionId;
 //Header oauthHeader;
 //Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
 
 private void showAccounts(String instanceUrl, String accessToken,
  PrintWriter writer) throws ServletException, IOException {
  HttpClient httpclient = new HttpClient();
  //HttpHost proxy = new HttpHost("" ,8080);
  //httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
  GetMethod get = new GetMethod(instanceUrl+ "/services/data/v36.0/query");
  // set the token in the header
  get.setRequestHeader("Authorization", "OAuth " + accessToken);
  NameValuePair[] params = new NameValuePair[1];
  params[0] = new NameValuePair("q",
    "SELECT Name, Id from Account LIMIT 100");
  get.setQueryString(params);
  try {
   httpclient.executeMethod(get);
   if (get.getStatusCode() == HttpStatus.SC_OK) {
    // Now lets use the standard java json classes to work with the
    // results
    try {
     JSONObject response = new JSONObject(
       new JSONTokener(new InputStreamReader(
         get.getResponseBodyAsStream())));
     System.out.println("Query response: "
       + response.toString(2));
     writer.write(response.getString("totalSize")
       + " record(s) returned\n\n");
     JSONArray results = response.getJSONArray("records");
     for (int i = 0; i < results.length(); i++) {
      writer.write(results.getJSONObject(i).getString("Id")
        + ", "
        + results.getJSONObject(i).getString("Name")
        + "\n");
     }
     writer.write("\n");
    } catch (JSONException e) {
     e.printStackTrace();
     throw new ServletException(e);
    }
   }
  } finally {
   get.releaseConnection();
  }
 }
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 
 public static void main(String[] args) throws ServletException, IOException  {
     
    
  DemoREST dmt = new DemoREST();
      boolean sucess = dmt.login();
      if(sucess){
      
      PrintWriter writer = new PrintWriter("C:/temp_plabon/SalesforceFiles/OutPut.txt");
      String accessToken = sessionId;
      String instanceUrl = "https://test.salesforce.com";
      if (accessToken == null) {
       writer.write("Error - no access token");
       return;
      }
      writer.write("We have an access token: " + accessToken + "\n"
        + "Using instance " + instanceUrl + "\n\n");
      dmt.showAccounts(instanceUrl, accessToken, writer);
    }
 private boolean login(){
  boolean success = false;
  try {
   
         ConnectorConfig config = new ConnectorConfig();
  Properties props = new Properties();  // template properties
  InputStream is = null;
         String authEndpoint ="https://test.salesforce.com/services/Soap/c/36.0";        
         config.setProxy("proxyhost" ,porxyPort);;
  config.setUsername("username");
  config.setPassword("Password");
         config.setAuthEndpoint(authEndpoint);
  Connection = new EnterpriseConnection(config);
  sessionId = connection.getSessionHeader().getSessionId();
  success = true;
  } catch (ConnectionException ce) {
   ce.printStackTrace();
  } //catch (IOException fe){
  // fe.printStackTrace();
  //}
  return success;
  
 }
}


===============Exception :=================

Mar 31, 2016 5:48:46 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
Mar 31, 2016 5:48:46 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Mar 31, 2016 5:49:07 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
Mar 31, 2016 5:49:07 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Mar 31, 2016 5:49:28 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: I/O exception (java.net.ConnectException) caught when processing request: Connection timed out: connect
Mar 31, 2016 5:49:28 PM org.apache.commons.httpclient.HttpMethodDirector executeWithRetry
INFO: Retrying request
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:381)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:243)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:230)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:377)
at java.net.Socket.connect(Socket.java:539)
at com.ibm.jsse2.SSLSocketImpl.connect(SSLSocketImpl.java:340)
at com.ibm.jsse2.SSLSocketImpl.<init>(SSLSocketImpl.java:68)
at com.ibm.jsse2.SSLSocketFactoryImpl.createSocket(SSLSocketFactoryImpl.java:5)
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:81)
at org.apache.commons.httpclient.protocol.SSLProtocolSocketFactory.createSocket(SSLProtocolSocketFactory.java:126)
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:706)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:386)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:170)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:396)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:324)
at com.cww.salesforce.restapi.DemoREST.showAccounts(DemoREST.java:71)
at com.cww.salesforce.restapi.DemoREST.main(DemoREST.java:281)

 
Daniel BallingerDaniel Ballinger
You should update your instanceUrl at the same time you read the sessionId in the login method. This is where the session will be valid.