您好我正在尝试使用Rest API连接到Salesforce,我想检索sObjects ..Implementing如下所示
void getsObjects() throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://na14.salesforce.com/services/data/v24.0/sobjects");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("X-HostCommonName", "ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("X-PrettyPrint", "1"));
nameValuePairs.add(new BasicNameValuePair("Host", "ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("X-Target-URI", "https://ap1.salesforce.com"));
nameValuePairs.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePairs.add(new BasicNameValuePair("Connection", "Keep-Alive"));
nameValuePairs.add(new BasicNameValuePair("Authorization", "00D90000000qUEp!AQQAQNnuPZqEX2oqAkeQLmvq.qsBfKIMa3GCJvE7atLv2Cjy94YZn5ezRH0bosXTFthnoMNt.WpDturXB1Ijxxxxxxxxxx"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("Content-Type","application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
System.out.println("Final response"+result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
即使我传递了授权密钥,它也会给出INVALID SESSION错误
12-11 14:50:18.108: W/DefaultRequestDirector(27014): Authentication error: Unable to respond to any of these challenges: {token=WWW-Authenticate: Token}
12-11 14:50:18.498: I/System.out(27014): Final response[{"errorCode":"INVALID_SESSION_ID","message":"Session expired or invalid"}]
我试图连接它2天但没有运气,有人能指出正确的方向,如何拨打休息电话。
答案 0 :(得分:2)
授权标题的格式应为Authorization: Bearer {sessionId}
,而您有Authorization:{sessionId}
您nameValuePairs
似乎包含http标头,但您没有创建标头,而是将它们传递给setEntity,后者设置http主体有效负载,而不是标头。
您正在创建一堆不与实际网址对齐的标准标头(如主机),无论如何都不需要这些标头。
尝试类似
的内容HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://na14.salesforce.com/services/data/v24.0/sobjects");
httpPost.setHeader("Authorization" , "Bearer " + sessionId)
StringEntity entity = new StringEntity("someJson", "UTF-8");
entity.setCotnentType("application/json");
httpPost.setEntity(entity)
HttpResponse response = httpclient.execute(httppost);
String result = EntityUtils.toString(response.getEntity());
System.out.println("Final response"+result);
您可能还想查看Force.com Android SDK,其中包含一堆用于访问API的帮助程序。