1

我用 Java 开发了一个 ODataClient 来创建新实体。我在创建新实体时遇到了困难。我主动查看了我的客户用 Fiddler 发送的所有消息。

        ODataEntityCreateRequest<ClientEntity>  request= 
            client.getCUDRequestFactory()
            .getEntityCreateRequest(new URI("http://localhost:8888/"), clientEntity);

    request.addCustomHeader("Content-Type", "application/json;odata.metadata=minimal");
    request.setAccept("application/json;odata=minimalmetadata");

    ODataEntityCreateResponse<ClientEntity> response = request.execute();

在我用 Fiddler 获得的正文的第一行下方:

17b
{"@odata.type":"#ODataDemo.Product", ....}

我使用 Fiddler 手动测试以创建一个新实体,消息正文的第一行应该是:

 {"odata.type":"ODataDemo.Product", ....}

我想知道是否可以使用 Odata 设置请求正文以删除“@”和“#”。

谢谢,

4

1 回答 1

1

我找到了解决这个问题的替代方案。我不完全使用 OData 库。我创建了发布请求的方法。

public void insertData(String entityName, Entity entity)
{       
    try {
        ResWrap<Entity> resW = new ResWrap<Entity>(new URI(this.baseURI.concat("/").concat(entityName)), "full", entity);
        ClientEntity clientEntity = this.client.getBinder().getODataEntity(resW);
        //String message = getMessageRebuild(client.getWriter().writeEntity(clientEntity, ContentType.APPLICATION_JSON));

        InputStream is = client.getWriter().writeEntity(clientEntity, ContentType.APPLICATION_JSON);

        if(is != null)
        {
            System.out.println("POST: "+post(this.baseURI.concat("/").concat(entityName), is));
            //System.out.println("POST:"+post("http://localhost:8888/"+entityName, is));
        }
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ODataSerializerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String post(String url,InputStream message) throws Exception{
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);
    //post.addHeader("Content-Type", "application/json;odata.metadata=minimal");
    //post.addHeader("Accept", "application/json;odata=verbose");
    post.addHeader("Content-Type", "application/json");
    post.addHeader("Accept", "application/json");
    HttpEntity entity = new ByteArrayEntity(IOUtils.toByteArray(message));
    post.setEntity(entity);
    HttpResponse response = client.execute(post);
    String result = EntityUtils.toString(response.getEntity());
    return result;
}

insertData 取两个参数:我生成的 entityName + Entity。我使用库 org.apache.http 将 http 消息发送到 OData 服务器。

于 2016-07-26T13:56:40.490 回答