I'm still working on getting the authentication working but having issues. I have been getting a 401 unauthorized error. All of the items I have hidden I am sure are correct values UNLESSS I need to add the security token to my password. Where have I gone wrong so far?
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
public class RestWork
{
private static final String CONSUMER_KEY = "hidden";
private static final String CONSUMER_SECRET = "hidden";
private static final String URL = "https://cs7.salesforce.com/services/apexrest/hidden/";
private static final String CONN_URL = "https://cs7.salesforce.com/services/oauth2/token";
public static void doWork()
{
HttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(URL);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("content-type", "application/json"));
nvps.add(new BasicNameValuePair("clientId", CONSUMER_KEY));
nvps.add(new BasicNameValuePair("clientSecret", CONSUMER_SECRET));
nvps.add(new BasicNameValuePair("redirectUri", "https://localhost:8443/RestTest/oauth/_callback"));
nvps.add(new BasicNameValuePair("environment", CONN_URL));
nvps.add(new BasicNameValuePair("grant_type", "password"));
StringEntity input = null;
try
{
input = new StringEntity("{\"username\": \"hidden\",\"password\": \"hidden\"}");
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
input.setContentType("application/json");
httpPost.setEntity(input);
for (NameValuePair h: nvps)
{
httpPost.addHeader(h.getName(), h.getValue());
}
try
{
HttpResponse response = client.execute(httpPost);
System.out.println("resp = " + response);
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
It prints out:
resp = HttpResponseProxy{HTTP/1.1 401 Unauthorized [Date: Fri, 25 Jul 2014 15:59:31 GMT, Set-Cookie: BrowserId=dsfaafffdsfafasd;Path=/;Domain=.salesforce.com;Expires=Tue, 23-Sep-2014 15:59:31 GMT, Expires: Thu, 01 Jan 1970 00:00:00 GMT, WWW-Authenticate: Token, Content-Type: application/json;charset=UTF-8, Transfer-Encoding: chunked]}
Best Answer
You are sending every attribute in Header than you should send all the attributes in a form-data. This will resolve your issue.
Refer the snapshot from postman crome plugin for a sample request.