Sungpah Lee
Sungpah Lee

Reputation: 1021

Android JSON post request with Ruby Web Application connection

I'm trying to connect Android json output with Ruby web application. I'm having difficulty to connect Android json post request with receiving from Ruby app. When Android jsonobject has another jsonobject inside, it is not recognised in the ruby app. Here is my code.

Android Code

JSONObject events_array = new JSONObject();
JSONObject parent=new JSONObject();

for (int i = 0; i < classtimeList.size(); i++) {
    events_array.put(classtimeList.get(i).toString(),priorityList.get(i).toString());
}

parent.put("token","token_information");
parent.put("class_type", "something");
parent.put("class_frequency", "5");
parent.put("course_id", "20");
parent.put("events_array", events_array);

String urlParameters = "info="+parent.toString();
Log.i("parameters", urlParameters);

This is a log info for parameters.

info={"token":"token_information","class_type":"something","class_frequency":"5","course_id":"20","events_array":{"3074":"3","3134":"1","3140":"1","3146":"3","3152":"1","3075":"3","3076":"3","3077":"3","3078":"3","3079":"3","3216":"3","3217":"3","3218":"1","3219":"3"}}

I pass this information to Ruby app and I am having difficulty to extract "events_array" information. Below is my Ruby Code.

My full Android code looks like

class apply extends AsyncTask<String, String, String> {

        ProgressDialog pd;
        private Exception exception;
        protected void onPreExecute() {

            pd = new ProgressDialog(ClassApply2.this);
            pd.setMessage("loading");
            pd.show();
        }

        protected String doInBackground(String... args) {
            String token = args[0];



            try {
                URL url = new URL("https://www.ringleplus.com/api/v1/apply/test");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                JSONObject events_array = new JSONObject();
                JSONObject parent=new JSONObject();

                for (int i = 0; i < classtimeList.size(); i++) {
                    events_array.put(classtimeList.get(i).toString(),priorityList.get(i).toString());
                }

                parent.put("token","token_information");
                parent.put("class_type", "something");
                parent.put("class_frequency", "5");
                parent.put("course_id", "20");
                parent.put("events_array", events_array);

                connection.setRequestMethod("POST");
                connection.setDoOutput(true);


                String urlParameters = "info=" + parent.toString();

                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
                dStream.writeBytes(urlParameters);


                //dStream.write(data);  // <!-- 여기에 url parameter가 들어감
                dStream.flush();
                dStream.close();

                Log.i("parameters", parent.toString());



                InputStream in = connection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                StringBuffer buffer = new StringBuffer();

                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line).append("\n");
                }
                reader.close();
                connection.disconnect();
                JSONObject jsonObj = null;

                jsonObj = new JSONObject(buffer.toString().trim());

                String output = jsonObj.getString("item");

                return output;

            }
            catch(Exception e) {
                Log.e("ERROR", e.getMessage(), e);
                return null;
            }
        }

        protected void onPostExecute(String response) {
            if(response == null) {
                response = "THERE WAS AN ERROR";
            }
            //progressBar.setVisibility(View.GONE);
            Log.i("INFO", response);

            if (pd != null) {
                pd.dismiss();
            }

            adapter.notifyDataSetChanged();

        }

Ruby Code

post :test do

    parsed_json = ActiveSupport::JSON.decode(params[:info].to_json)
    token = parsed_json["token"]
    events_array = parsed_json["events_array"]

    output = Array.new      

    if events_array != nil 
        events_array.each do |start_time, priority|
            if priority.to_i == 1 || priority.to_i == 2
              userapply = Userapply.new
              userapply.classtime_id = start_time
              userapply.user_id = user.id
              userapply.priority = priority
              userapply.save
              output << {:userapply_id => userapply.id, :classtime_id => userapply.classtime_id, :user_id => userapply.user_id, :priority => userapply.priority}
            end
        end
    end


    return {status: 'ok', item: events_array}

end

What it supposed to be returned is the information about events_array (i.e. {"3074":"3","3134":"1","3140":"1","3146":"3","3152":"1","3075":"3","3076":"3","3077":"3","3078":"3","3079":"3","3216":"3","3217":"3","3218":"1","3219":"3"} )

but, the Android output log is I/INFO: events_array

but the token extraction seems working.

token = parsed_json["token"]

If this works, then my gut feeling is parsed_json["events_array"] also should work in some sense. But I'm not stuck here.

If this is resolved, then I want to receive parsed_json["events_array"] as a hash information and want to process the full code and get the "output" instead of events_array to check why this doesn't work.

Please let me know if there is anything I'm missing. I really need some help.

Looking forward to seeing anyone's reply.

Upvotes: 0

Views: 213

Answers (1)

Vsevolod Poletaev
Vsevolod Poletaev

Reputation: 1532

I finally figured out where the problem came from. I compared what you send to your server with curl in comment above, and what you try to send from android. And these two things are completly difirent. To send the same from androdid, you should form your urlParameter like that:

JSONObject info = new JSONObject();
info.put("info",parent);
urlParameters = info.toString();

And don't forget to do connection.setRequestProperty("Content-Type", "application/json") after connection.setDoOutput(true).

I tested it outside android, and it returned pretty the same as curl command from your comment above. It should work just fine in android.

PS: Please, be more more attentive next time.

Upvotes: 3

Related Questions