Simple JSON RPC Client for Android

This is a simple JSON RPC Client for Android. I wrote this class for one of my Android projects that needs to connect to external JSON RPC API. Feel free to use it, download the files at the bottom of this post..;)

JSON RPC Client

package net.londatiga.android;

import net.londatiga.android.Cons;
import net.londatiga.android.Debug;
import net.londatiga.android.StringUtil;

import java.io.InputStream;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * Simple JSON RPC Client
 *
 * @author Lorensius W. L. T <lorenz@londatiga.net>
 *
 */
public class JSONRPCClient {
	private String mBaseUrl;
	private String mMethod;

	private HashMap<String, Integer> mIntParams;
	private HashMap<String, String> mStrParams;

	public JSONRPCClient() {
		mBaseUrl 	= Cons.API_URL;

		mIntParams 	= new HashMap<String, Integer>();
		mStrParams	= new HashMap<String, String>();
	}

	public void setBaseUrl(String url) {
		mBaseUrl = url;
	}

	public void setMethod(String method) {
		mMethod = method;
	}

	public void addParam(String name, String value) {
		mStrParams.put(name, value);
	}

	public void addParam(String name, int value) {
		mIntParams.put(name, value);
	}

	public JSONObject connect() throws Exception {
		HttpClient httpClient 	= new DefaultHttpClient();
		HttpPost httpPost 		= new HttpPost(mBaseUrl);
		JSONObject jsonResult	= null;

		try {
			JSONObject params 	= buildParam();
			String entity		= params.toString();

			Debug.i("POST " + mBaseUrl);
			Debug.i("Data: " + entity);

			HttpParams httpParams 		= httpClient.getParams();

			HttpConnectionParams.setConnectionTimeout(httpParams, Cons.HTTP_CONNECTION_TIMEOUT);
			HttpConnectionParams.setSoTimeout(httpParams, Cons.HTTP_SOCKET_TIMEOUT);

			httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
	        httpPost.setEntity(new StringEntity(entity));

	        HttpResponse httpResponse 	= httpClient.execute(httpPost);

			HttpEntity httpEntity 		= httpResponse.getEntity();

			if (httpEntity == null) throw new Exception("");

			InputStream stream 			= httpEntity.getContent();

			if (stream != null) {
				String strResponse 		= StringUtil.streamToString(stream);

				Debug.i(strResponse);

				JSONObject jsonResponse = (JSONObject) new JSONTokener(strResponse).nextValue();

				if (!jsonResponse.isNull("result")) {
					jsonResult = jsonResponse.getJSONObject("result");
				}

				stream.close();
			}
		} catch (Exception e) {
			throw e;
		}

		return jsonResult;
	}

	private JSONObject buildParam() {
		JSONObject object = new JSONObject();
		JSONObject params = new JSONObject();

		try {
			if (mIntParams.size() > 0) {
				for (String key : mIntParams.keySet()) {
					params.put(key, mIntParams.get(key));
				}
			}

			if (mStrParams.size() > 0) {
				for (String key : mStrParams.keySet()) {
					params.put(key, mStrParams.get(key));
				}
			}

			object.put("jsonrpc", 	"2.0");
			object.put("method", 	mMethod);
			object.put("params", 	params);
			object.put("id", 		1);

		} catch (Exception e) { }

		return object;
	}
}

How to use it:

public String getData(String param1, String param2, String param3) throws Exception {
		String res = "";

		try {
			JSONRPCClient jsonRpc = new JSONRPCClient();

			jsonRpc.setMethod("MyRPCMethod"); //set method name

			//set parameters
			jsonRpc.addParam("param1", 	param1);
			jsonRpc.addParam("param2", 	param2);
			jsonRpc.addParam("param3", 	param3);

			JSONObject jsonObj = jsonRpc.connect();

			if (jsonObj != null) {
				//parsing the returned json here
			}
		} catch (Exception e) {
			throw e;
		}

		return res;
	}

Download Simple JSON RPC Client for Android

facebooktwittergoogle_plusredditpinterestlinkedinmailby feather

Comments

  1. yasser says

    Thanks for this great post, i have few questions:

    What is the purpose of the class JSONRPC_Client

    and should i use any libraries or something like that ?

Leave a Reply

Your email address will not be published. Required fields are marked *