Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As I haven't gotten any replies to my previous question ( help with jersey client ) I thought I'd try a different approach - so here goes. I have a media server running on my LAN which has a jsonrpc API interface, it accepts a request in the form

"{id=1, method=slim.request, params=["-",["artists","0","-1"]]}"


And returns json

I can access it successfully using a Jersey client but would like to know how to do it without using Jersey as I want my program to be usable on Android which doesn't to my knowledge have a Jersey client available. Obviously this will be written in Java.
Posted

1 solution

Got it figured this does the job nicely
package com.pjksolutions.jasonrpc;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HTTPUtils
{
	String Server;
	String Request;
	URL url;
	HttpURLConnection conn;


	public HTTPUtils()
	{
	}

	public HTTPUtils(String Server)
	{
		this();
		this.Server = Server;
	}


	private void InitServer()
	{
		try
		{
			this.url = new URL(this.Server);
			this.conn = (HttpURLConnection) this.url.openConnection();
			this.conn.setConnectTimeout(10000);
			this.conn.setReadTimeout(10000);
			this.conn.setRequestMethod("POST");

			this.conn.setDoOutput(true);
			this.conn.setDoInput(true);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
	}


    public String PostRequest(String Request)
    {

        this.Request = Request;

        try 
		{
			this.InitServer();
            DataOutputStream wr = new DataOutputStream(
				this.conn.getOutputStream());
            wr.writeBytes(this.Request);
            wr.flush();
            wr.close();

            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();

            while ((line = rd.readLine()) != null)
			{
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        }
        catch (Exception e)
		{
			return "error";
		}
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900