我正在创建一个可以从我的 Rails 应用程序添加/编辑/删除项目的 Android 应用程序。我可以使用 HttpGet 调用使用 Android 应用程序成功添加项目,但我想做的是轻松获取新创建项目的 ID,以便我可以使用 ID 启动活动。有没有办法从我的 HttpGet 请求中获取返回值?
这是我的安卓代码:
// Add a new user project
public class AddProjectTask extends AsyncTask<String, Void, HttpEntity>{
@Override
protected HttpEntity doInBackground(String... urls){
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(urls[0]);
Log.d(TAG, "url: " + urls[0]);
get.setHeader("Content-Type", "application/json");
HttpResponse response = null;
try{
Log.d(TAG, "attempting to execute post");
response = client.execute(get);
Log.d(TAG, "response: " + response);
} catch(HttpResponseException e){
e.printStackTrace();
Log.e("ClientProtocol", ""+e);
} catch(IOException e){
e.printStackTrace();
Log.e("IO", "" + e);
}
HttpEntity result = response.getEntity();
String httpResponse="";
try {
httpResponse = inputStreamToString(result.getContent()).toString();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "httpResponse: " + httpResponse);
return result;
}
protected void onPostExecute(HttpEntity result){
if(result!=null){
Toast.makeText(getApplicationContext(), "Added Project", Toast.LENGTH_LONG).show();
// redirect to activity using ID of new project ???
}
}
}
我的 Rails 项目控制器:
def create
@project = Project.new(params[:project])
numUntitled = Project.where("user_id"=>current_user.id).where("title like ?", "%Untitled%").count
logger.debug("numUntitled: #{numUntitled}")
@project.title = "Untitled-"+ (numUntitled+1).to_s()
@project.built = false
@project.user = current_user
# add default project overview step
@step = @project.steps.build
# set step number to 0
@step.position = 0
@step.name = "Project Overview"
@step.description = "Project description"
@step.published_on = DateTime.current
respond_to do |format|
if @project.save
format.html { redirect_to @project, :notice => 'Project was successfully created.' }
format.json { render :json => @project, :status => :created, :location => @project }
else
format.html { render :action => "new" }
format.json { render :json => @project.errors, :status => :unprocessable_entity }
end
end
end
此外,我似乎已经通过在我的 Android 应用程序中编写另一个异步任务来获取项目并获取最近创建的项目的 id 来解决这个问题,但这似乎是额外的工作,特别是如果我可以通过某种方式获取项目 id httpput 请求。