使用Salesforce REST API更新记录 - 修补程序方法无效

时间:2013-06-24 05:45:52

标签: rest salesforce updates

我正在尝试更新驻留在salesforce表中的记录。我使用Java HttpClient REST API来做同样的事情。使用PATCH更新Salesforce中的记录时出错。

PostMethod post = new PostMethod(
    instanceUrl + "/services/data/v20.0/sobjects/" +
    objectName + "/" + Id + "?_HttpMethod=PATCH"
);

[{“message”:“不允许使用HTTP方法'PATCH'。允许使用HEAD,GET,POST”,“errorCode”:“METHOD_NOT_ALLOWED”}]

还尝试执行以下操作:

PostMethod post = new PostMethod(
    instanceUrl + "/services/data/v20.0/sobjects/" + objectName + "/" + Id)
    {
        public String getName() { return "PATCH"; 
    }
};

这也会返回相同的错误。我们使用apache tomcat和commons-httpclient-3.1.jar库。请告知如何做到这一点。

3 个答案:

答案 0 :(得分:1)

请检查您是否使用了正确的PATCH方法,请参阅:Insert or Update (Upsert) a Record Using an External ID

另外检查你的REST URL是否正确,可能你的objectId没有从Javascript正确传递。

ObjectName是Salesforce表的名称,即' Contact'。 Id是您要在表格中更新的特定记录的ID。

类似:

答案 1 :(得分:0)

我认为你知道,公共httpclient 3.1没有PATCH方法,而且库已经过了生命周期。在上面的代码中,您尝试将HTTP方法添加为查询参数,这实际上没有意义。

SalesForce Developer Board所示,你可以这样做:

HttpClient httpclient = new HttpClient();
PostMethod patch = new PostMethod(url) {
  @Override
  public String getName() {
    return "PATCH";
  }
};
ObjectMapper mapper = new ObjectMapper();
StringRequestEntity sre = new StringRequestEntity(mapper.writeValueAsString(data), "application/json", "UTF-8");
patch.setRequestEntity(sre);
httpclient.executeMethod(patch);

这允许您在不切换httpclient库的情况下进行PATCH。

答案 2 :(得分:0)

我创建了这个方法来通过 Java HttpClient 类发送补丁请求。 我使用的是 JDK V.13

private static VarHandle Modifiers; // This method and var handler are for patch method
    private static void allowMethods(){
        // This is the setup for patch method
        System.out.println("Ignore following warnings, they showed up cause we are changing some basic variables.");

        try {

            var lookUp = MethodHandles.privateLookupIn(Field.class, MethodHandles.lookup());
            Modifiers = lookUp.findVarHandle(Field.class, "modifiers", int.class);

        } catch (IllegalAccessException | NoSuchFieldException e) {
            e.printStackTrace();

        }
        try {

            Field methodField = HttpURLConnection.class.getDeclaredField("methods");
            methodField.setAccessible(true);
            int mods = methodField.getModifiers();

            if (Modifier.isFinal(mods)) {
                Modifiers.set(methodField, mods & ~Modifier.FINAL);
            }

            String[] oldMethods = (String[])methodField.get(null);

            Set<String> methodsSet = new LinkedHashSet<String>(Arrays.asList(oldMethods));
            methodsSet.addAll(Collections.singletonList("PATCH"));
            String[] newMethods = methodsSet.toArray(new String[0]);
            methodField.set(null, newMethods);

        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }