rob*_*ong 5 rest android json http-post ruby-on-rails-3
我目前正在开发一个通过XML和JSON与Ruby on Rails应用程序连接的Android应用程序.
我现在可以通过XML从我的网站上提取所有帖子,但我似乎无法通过JSON发布.
我的应用程序当前从一个看起来像这样的形式的表单构建一个JSON对象:
{
"post": {
"other_param": "1",
"post_content": "Blah blah blah"
}
}
Run Code Online (Sandbox Code Playgroud)
在我的服务器上,我相信我的帖子控制器中的Create方法设置正确:def create @post = current_user.posts.build(params [:post])
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render json: @post, status: :created, location: @post }
format.xml { render xml: @post, status: :created, location: @post }
else
format.html { render action: "new" }
format.json { render json: @post.errors, status: :unprocessable_entity }
format.xml { render xml: @post.errors, status: :unprocessable_entity }
end
end
end
Run Code Online (Sandbox Code Playgroud)
在我的Android应用程序中,我有一个方法,将我之前发布的JSON对象作为参数以及用于进行身份验证的用户名和密码(身份验证正在运行我已经对其进行了测试,并且是简单的HTTP身份验证可能不是最佳选择但它是一个快速而又脏的修复程序)然后它通过HTTP POST将JSON对象发送到rails服务器.这是方法:
public static void sendPost(JSONObject post, String email, String password)
{
DefaultHttpClient client = new DefaultHttpClient();
client.getCredentialsProvider().setCredentials(new AuthScope(null,-1), new UsernamePasswordCredentials(email,password));
HttpPost httpPost = new HttpPost("http://mysite.com/posts");
JSONObject holder = new JSONObject();
try {
holder.put("post", post);
StringEntity se = new StringEntity(holder.toString());
Log.d("SendPostHTTP", holder.toString());
httpPost.setEntity(se);
httpPost.setHeader("Content-Type","application/json");
} catch (UnsupportedEncodingException e) {
Log.e("Error",""+e);
e.printStackTrace();
} catch (JSONException js) {
js.printStackTrace();
}
HttpResponse response = null;
try {
response = client.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol",""+e);
} catch (IOException e) {
e.printStackTrace();
Log.e("IO",""+e);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
Log.e("IO E",""+e);
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
目前,当我调用此方法并将其传递给正确的JSON对象时,它没有做任何事情,我不知道为什么或如何弄清楚出了什么问题.
我的JSON仍然格式化错误,是否真的需要围绕其他数据持有?或者我是否需要使用HTTP POST以外的其他内容?或者这只是Rails结尾的东西?路线或控制器不对吗?
如果有人能指出我正确的方向,我会非常感激,因为我不知道从哪里开始.
我不喜欢 Rails,但也许是你必须禁用的csrf验证(以前发生在我身上)。
您可以按照以下代码检查响应的状态:
HttpResponse response = client.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
Log.i(TAG, "HTTP Status Code: " + statusLine.getStatusCode());
Run Code Online (Sandbox Code Playgroud)
编辑:我有这个JSONResponseHandler,当我执行 API 请求时,它对我来说工作得很好。您只需将其设置为 HttpClient 对象的执行方法中的第二个参数即可。响应将是一个 JSONObject,如果请求不成功,它将抛出异常。也许这可以帮助您更快地绕过这个问题。
| 归档时间: |
|
| 查看次数: |
3131 次 |
| 最近记录: |