简体   繁体   English

Java和MS CRM 2016 Web API更新

[英]Java and MS CRM 2016 Web API Updates

i have a java application and i am trying to update an opportunity via the crm web api. 我有一个Java应用程序,我试图通过crm web api更新机会。 When i try to use a Non-Standard HTTP Method like PATCH (which is neccessary for the update) and override it with the "X-HTTP-Method-Override" like i found it in various example codes, it doesnt work. 当我尝试使用像PATCH这样的非标准HTTP方法(这是更新所必需的)并使用“X-HTTP-Method-Override”覆盖它,就像我在各种示例代码中找到它一样,它不起作用。

Code for the opportunity update: 机会更新代码:

public int updateOpportunity(OpportunityDaoModel model) throws IOException, URISyntaxException {
JSONObject opportunity = new JSONObject();
opportunity.put("name", model.getTopic());

HttpURLConnection connection = null;
URL url = new URL(RESOURCE + "/api/data/"+API_VERSION+"/opportunities(" + model.getCrmguid() + ")");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
connection.setRequestProperty("OData-MaxVersion", "4.0");
connection.setRequestProperty("OData-Version", "4.0");
connection.setRequestProperty("Accept", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + token);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.connect();

OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(opportunity.toString());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
return responseCode;
}

After executing this method i get the following error: 执行此方法后,我收到以下错误:

{
 "error":{
   "code":"","message":"Unmapped Request found, PathTemplate:~/entityset/key, HttpVerb:POST","innererror":{
     "message":"Unmapped Request found, PathTemplate:~/entityset/key, HttpVerb:POST","type":"Microsoft.Crm.CrmHttpException","stacktrace":"   at Microsoft.Crm.Extensibility.OData.EntityController.HandleUnmappedRequest(ODataPath path)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
   }
 }
}

After i didn't find any information on the web for this error i tried a different entry and wanted to use the single attribute update via PUT. 在我没有在网上找到任何关于此错误的信息后,我尝试了一个不同的条目,并希望通过PUT使用单个属性更新。 This succeeds for normal attributes (like the name attribute on many entities) but when i try to update a lookup field i get a different error. 这对于普通属性(如许多实体上的name属性)成功,但是当我尝试更新查找字段时,我得到了不同的错误。 But first my method: 但首先是我的方法:

Code for the single attribute update: 单个属性更新的代码:

public int updateAttribute(String entity, String id, String attribute, String value) throws IOException, URISyntaxException {
JSONObject opportunity = new JSONObject();
HttpURLConnection connection = null;
String urlString = "";
if(attribute.contains("@odata.bind")) { // lookup value
    urlString = RESOURCE + "/api/data/"+API_VERSION+"/"+entity+"(" + id + ")";
        opportunity.put(attribute, value);
} else { // text value
        urlString = RESOURCE + "/api/data/"+API_VERSION+"/"+entity+"(" + id + ")/" + attribute;
        opportunity.put("value", value);
}
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("PUT");
connection.setRequestProperty("OData-MaxVersion", "4.0");
connection.setRequestProperty("OData-Version", "4.0");
connection.setRequestProperty("Accept", "application/json");
connection.addRequestProperty("Authorization", "Bearer " + token);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.connect();

OutputStreamWriter out = new     OutputStreamWriter(connection.getOutputStream());
out.write(opportunity.toString());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
return responseCode;
}

i call this method via 我叫这个方法通过

 updateAttribute("opportunities", model.getCrmguid(), "lookupentityid@odata.bind", "/entityendpointwiths("+model.getProgress()+")");

The error message: 错误消息:

{
 "error":{
    "code":"","message":"Operation not supported on opportunity","innererror":{
    "message":"Operation not supported on opportunity","type":"Microsoft.Crm.CrmHttpException","stacktrace":"   at Microsoft.Crm.Extensibility.OData.EntityController.PutEntity(String entityName, String key, EdmEntityObject entity)\r\n   at lambda_method(Closure , Object , Object[] )\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n   at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"
    }
  }
 }

Thank you for any help. 感谢您的任何帮助。

Kind regards, Dennis 亲切的问候,丹尼斯

If anyone else should be in this position i am happy to present you my answer. 如果其他人应该处于这个位置,我很乐意向您提供我的答案。 Instead of using the x-http-override header you should use the HTTPPatch-Class of java. 您应该使用java的HTTPPatch-Class,而不是使用x-http-override标头。

method: 方法:

public String updateAttribute(String entity, String id, List<Map<String, Object>> parameters) throws IOException, URISyntaxException {
JSONObject object = new JSONObject();
    for (Map<String, Object> map : parameters) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            object.put(key, value);
        }
    }

    String urlString = "";
    urlString = RESOURCE + "/api/data/"+API_VERSION+"/"+entity+"(" + id + ")/";
    StringEntity stringEntity = new StringEntity(object.toString());

    URL url = new URL(urlString);
    HttpPatch httpPatch = new HttpPatch(urlString);
    httpPatch.addHeader("OData-MaxVersion", "4.0");
    httpPatch.addHeader("OData-Version", "4.0");
    httpPatch.addHeader("Accept", "application/json");
    httpPatch.addHeader("Authorization", "Bearer " + token);
    httpPatch.addHeader("Content-Type", "application/json");
    httpPatch.setEntity(stringEntity);

    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpResponse httpResponse = httpClient.execute(httpPatch);

int responseCode =  httpResponse.getStatusLine().getStatusCode();

if (responseCode > 299) {
    InputStream inputStream = httpResponse.getEntity().getContent();
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) != -1) {
        result.write(buffer, 0, length);
    }

    throw new IOException(result.toString("UTF-8"));
}

return responseCode;
}

Calling the method via: 通过以下方式调用方法:

List<Map<String,Object>> opportunityParameterList = new ArrayList<>();
Map<String, Object> opportunityParameters = new HashMap<>();      
opportunityParameters.put("name", opportunityDaoModel.getTopic());
opportunityParameters.put("lookupfield@odata.bind", "/lookupentityendpoint("+opportunityDaoModel.getProgress()+")");
opportunityParameterList.add(opportunityParameters);
this.crmHelper.updateAttribute("opportunities", opportunityDaoModel.getCrmguid(), opportunityParameterList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Dynamics CRM 2016.Web API Auth。我有令牌,现在是什么? - Dynamics CRM 2016.Web API Auth. I have token, now what? How to Create Case in Microsoft Dynamics CRM 2016 (Version 8) using webservices or REST API in JAVA or C#? - How to Create Case in Microsoft Dynamics CRM 2016 (Version 8) using webservices or REST API in JAVA or C#? 尝试通过java中的web api连接Microsoft dynamics crm - trying to connect Microsoft dynamics crm by web api in java 从Java连接MS Dynamics CRM 2011 - Connect MS Dynamics CRM 2011 from java 将 Java 应用程序连接到 Microsoft CRM 2013 或 2016 的方法 - Ways to connect a Java Application to Microsoft CRM 2013 or 2016 使用adal java 500内部服务器错误Ms动态CRM - 500 Internal Server error Ms dynamics CRM using adal java 如何为MS Dynamics CRM 2011服务生成Java代码 - How to generate Java code for MS Dynamics CRM 2011 Service 通过 SOAP/Java 在 MS Dynamics CRM 2011 中创建产品 - Create Product in MS Dynamics CRM 2011 via SOAP/Java 如何通过 Java 连接在 Azure 云上运行的 Dynamics CRM 2016 实例? - How to connect Dynamics CRM 2016 instance running on Azure Cloud through Java? 适用于Java的CRM Dynamics Online 2016 Azure SDK接收带有500错误代码的BrokeredMessages - CRM Dynamics Online 2016 Azure SDK for Java receive BrokeredMessages with 500 error code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM