0

我要转换的 CURL 是

curl –insecure -H "Authorization: Bearer c25laGEyMDE0QHZ5b21sYWJzLmNvbTpwdW5lQDEyM2lSWWx6MFdtbjBxRjExcDVyQTE5eDRNNVk" -H "Content-Type: application/json" -d @Incident.txt https://na15.salesforce.com/services/apexrest/Incident/

我正在使用的java代码是这样做的

import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Test {

    public static void main(String[] args) {
        try {
            String url = "https://na15.salesforce.com/services/apexrest/Incident/";

            URL obj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);

            conn.setRequestMethod("PUT");

            String userpass = "username" + ":" + "password+securitytoken_of_force.com";
            String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

            System.out.println(basicAuth);
            conn.setRequestProperty ("Authorization : Bearer", basicAuth);

            String data =  "{\"srd1\":\"HardwareIssue\"}";
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
            out.write(data);
            out.close();

            new InputStreamReader(conn.getInputStream());   
        } catch (Exception e) {
            e.printStackTrace();
        }
     } 
 } 

但是在执行代码时,我面临以下错误

“服务器返回 HTTP 响应代码:URL 的 401:https ://na15.salesforce.com/services/apexrest/Incident/ 。”

我是这样做的新手,请建议。

4

2 回答 2

0

您似乎正在尝试混合基本身份验证和 oauth 令牌,这不起作用,授权标头中传递的 Bearer 令牌需要通过 OAuth 流程之一获得。有很多关于此的文档和文章,从在线帮助开始

于 2014-05-08T16:00:16.620 回答
0

错误 401 表示您无权访问 URL/资源。我尝试运行您的 cURL 代码,它还返回了 401 和此消息:

[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]

也许你没有传递正确的Authorization标题。

于 2014-05-08T10:56:54.067 回答