我在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设置请求的正文以删除“@”和“#”。
谢谢,
答案 0 :(得分: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 +我生成的实体。 我使用librairie org.apache.http将http消息发送到OData服务器。