我目前正在做一个项目,我们被要求从服务器存储和接收食谱。配方以 json 格式存储在服务器 ip + 一个 id 上。我一直在考虑一种创建 ID 的好方法,该 ID 保证不会在我们提交的两个食谱之间重叠。是否有创建这些 ID 的标准例外方法,或者只存储一个 int 跟踪最大 ID 并在有人想要存储配方服务器端时提取它是一个更好的主意?
在此先感谢,
优雅
public void addRecipe(Recipe recipe, String URL) throws IllegalStateException, IOException{
// TODO Implement the server-side ID tracking
//int id = getID();
//recipe.setId(id);
HttpPost httpPost = new HttpPost(URL+recipe.getId());
StringEntity stringEntity = null;
try {
stringEntity = new StringEntity(gson.toJson(recipe));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPost.setHeader("Accept","application/json");
httpPost.setEntity(stringEntity);
HttpResponse response = null;
response = httpclient.execute(httpPost);
// String status = response.getStatusLine().toString();
// System.out.println(status);
HttpEntity entity = response.getEntity();
try {
// May need if statement, check isStreaming();
entity.consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//May possibly need to deallocate more resources here. No 4.0 implementation of releaseconnection();
}
也许这段代码会有所帮助?这就是我将食谱存储到服务器上的方式。