Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Post To Rails From Android

I'm currently working on an android app that interfaces with a Ruby on Rails app through XML and JSON.

I can currently pull all my posts from my website through XML but I can't seem to post via JSON.

My app currently builds a JSON object from a form that looks a little something like this:

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

On my server I believe the Create method in my Posts Controller is set up 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

And in my android app I have a method that takes that JSON Object I posted earlier as a parameter along with the username and password for being authenticated (Authentication is working I've tested it, and yes Simple HTTP authentication is probably not the best choice but its a quick and dirty fix) and it then sends the JSON Object through HTTP POST to the rails server. This is that method:

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

}

Currently when I call this method and pass it the correct JSON Object it doesn't do anything and I have no clue why or how to figure out what is going wrong.

Is my JSON still formatted wrong, does there really need to be that holder around the other data? Or do I need to use something other than HTTP POST? Or is this just something on the Rails end? A route or controller that isn't right?

I'd be really grateful if someone could point me in the right direction, because I don't know where to go from here.

like image 245
robertlong Avatar asked Nov 04 '22 10:11

robertlong


1 Answers

I'm not into Rails, but maybe is a csrf validation that you have to disable (it happened to me before).

You can follow this code to check the status of the response:

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

EDIT: I have this JSONResponseHandler that has worked fine for me when I do API requests. You just have to set it as a second parameter in your execute method of the HttpClient object. The response will be a JSONObject, and it will throw an exception if the request was unsuccessful. Maybe this could help you to bypass this issues quicker.

like image 162
FernandoEscher Avatar answered Nov 09 '22 12:11

FernandoEscher