JSON Post To Rails with Android

I am currently working on an Android application that interacts with a Ruby on Rails application through XML and JSON.

Currently, I can pull all my messages from my site through XML, but I can not send a message through JSON.

My application is currently creating a JSON object from a form that looks something like this:

{
    "post": {
        "other_param": "1", 
        "post_content": "Blah blah blah"
    }
}

On my server, I am sure that the Create method in my message controller is configured correctly: 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

Android , JSON, , ( , HTTP-, , , ), JSON HTTP POST . :

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();
        }
    }

}

, JSON, , , , .

JSON , ? - , HTTP POST? - Rails? ?

, - , , .

+5
1

Rails, , , csrf , ( ).

, :

HttpResponse response = client.execute(httpPost);       
StatusLine statusLine = response.getStatusLine();
Log.i(TAG, "HTTP Status Code: " + statusLine.getStatusCode());

EDIT: JSONResponseHandler, , API. HttpClient. JSONObject, , . , .

+2

All Articles