• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • About
  • Projects
    • GStaticMap WP Plugin
  • Contact
  • Privacy Policy

Lorenz Blog

All About Web & Mobile Application Development

  • Featured Articles
  • Gadgets
    • Android
    • Blackberry
  • Programming
    • Android
    • PHP
    • Java Script
    • MySQL
    • Postgresql
    • Flex
    • Web
  • Software
    • Mac OS
    • Windows
    • Linux
  • Web
You are Here » Home >> Information Technology >> Programming >> Android >> Simple JSON RPC Client for Android

Simple JSON RPC Client for Android

January 11, 2014 by Lorensius Londa 2 Comments

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

[ad]

Download Simple JSON RPC Client for Android

Facebooktwitterredditpinterestlinkedinmailby feather

Related posts:

  1. How to Send Message to Google Cloud Messaging (GCM) Server Using JSON and PHP
  2. Sample Code to Get MD5 Checksum of a File in Android
  3. How to Setup Google Apps Email Client on Android
  4. How to Use Foursquare API on Android Application

Filed Under: Android, Featured Articles Tagged With: Android, json class, json parser, json rpc client

About Lorensius Londa

Passionate web and mobile application developer. Co-founder of TRUSTUDIO, loves programming, Android, aviation, travelling, photography, coffee and gym mania.

Reader Interactions

Comments

  1. yasser says

    August 4, 2014 at 3:17 am

    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 ?

    Reply
  2. Faiz says

    February 18, 2015 at 3:55 am

    Hi,
    i have the following request to jsonrpc server:
    curl -u admin:e4d4face52f2e3dc22b43b2145ed7c58ce66e26b384d73592c -d “{\”jsonrpc\”: \”2.0\”, \”method\”: \”feed.list\”, \”id\”: 1}” http://localhost/minifluxR/jsonrpc.php

    how can i do the same using your client?

    Thanks

    Reply

Leave a Reply Cancel reply

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

Primary Sidebar

About Me

A husband, father of two, passionate software developer, diy lover and home baker who loves to learn new things. Read More…

  • Facebook
  • GitHub
  • Google+
  • Instagram
  • Twitter
  • YouTube

Featured Articles

How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Blue Bamboo P25 Printer Android Demo Application With Source Code

Simple JSON RPC Client for Android

How to Send Message to Google Cloud Messaging (GCM) Server Using JSON and PHP

Footer

Recent Comments

  • Aditya Dabas on About
  • Ayten Göksenin Barutçu on How to Make Android Map Scrollable Inside a ScrollView Layout
  • mang jojot on About
  • Hussain on How to Programmatically Scan or Discover Android Bluetooth Devices

Recent Posts

  • How to Fix Blank Screen on WordPress Add/Edit Post Page
  • How to Programmatically Restart the ESP32 Board
  • How to Get Hardware Info of ESP32
  • How to Setup MQTT Server Using Mosquitto and Libwebsocket on Freebsd

Latest Tweets

  • @tricahyono_bowo @infobandung @infobdg Wah kejauhan om 355 days ago
  • Wilujeng enjing sadayana..Mohon info tempat powder coating dan sandblasting yg recommended di Bandung dunk @infobandung @infobdg359 days ago

Copyright © 2023 · Magazine Pro on Genesis Framework · WordPress · Log in