Search code examples
androidandroid-studioandroid-jsonandroid-webservice

To connect with a web-service there is two options, either use a Library or "JSONParser" Class. Which is better? which one is safe?


I am asking this because I am beginner in android development.

I am doing a core-banking application, so I used JSON Parser class to connect with REST Web-Service,

JSONParser Class is,

package com.anvinsolutions.digicob_custmate;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;

public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;// = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;

public JSONObject makeHttpRequest(String url, String method,
                                  HashMap<String, String> params) {

    sbParams = new StringBuilder();
    int i = 0;
    for (String key : params.keySet()) {
        try {
            if (i != 0){
                sbParams.append("&");
            }
            sbParams.append(key).append("=")
                    .append(URLEncoder.encode(params.get(key), charset));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        i++;
    }

    if (method.equals("POST")) {
        // request method is POST
        try {
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(true);

            conn.setRequestMethod("POST");

            conn.setRequestProperty("Accept-Charset", charset);

            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);

            conn.connect();

            paramsString = sbParams.toString();

            wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes(paramsString);
            wr.flush();
            wr.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    else if(method.equals("GET")){
        // request method is GET

        if (sbParams.length() != 0) {
            url += "?" + sbParams.toString();
        }

        try {
            urlObj = new URL(url);

            conn = (HttpURLConnection) urlObj.openConnection();

            conn.setDoOutput(false);

            conn.setRequestMethod("GET");

            conn.setRequestProperty("Accept-Charset", charset);

            conn.setConnectTimeout(15000);

            conn.connect();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    try {
        //Receive the response from the server
        InputStream in = new BufferedInputStream(conn.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));

        result = new StringBuilder(); // add this line
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        Log.d("JSON Parser", "result: " + result.toString());

    } catch (IOException e) {
        e.printStackTrace();
    }

    conn.disconnect();

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(result.toString());
    } catch (Exception e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON Object
    return jObj;
}
}

and i am confused if this method have any problem with Security,performance? i didn't try any Libraries till now, i just used this JSONParaser Class. i think its easy to work with a JSONParser Class..

WHICH ONE TO USE? thank you in advance! ;)


Solution

  • You never use JSonParser class to connect to a Web service. From your code, looks like you are using Vanilla HttpURLConnection class for connecting to service and using the JSonParser class to parse the result which is good and simple if you only have a couple of web requests to make in your application.

    However since you said, it's banking application, you might have to think about scalability, multiple requests and stuffs like that. You could well try to handle them by yourself but the suggested way would be to use one of the tried and tested network libraries available for Android. Retrofit and Volley are two such and there are many more. The choice of the library to use is based on your use cases.

    @AJay has already pointed to a page for comparison. Have a look.

    Onto your next thing, about the parsing, performance is one of the key factors. Have a look at the below link for the options you have - http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/

    I would say GSon is pretty good among all. We use it extensively in our in-house products.