edu.xjtu.qxcamerabridge.JSONActionWrapper.java Source code

Java tutorial

Introduction

Here is the source code for edu.xjtu.qxcamerabridge.JSONActionWrapper.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.xjtu.qxcamerabridge;

import java.io.IOException;
import java.util.List;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author ZhipingJiang
 */
public class JSONActionWrapper {

    public static JSONObject jsonrpc(String service, String methodName, List<Object> params) {

        JSONArray paramArray = new JSONArray(params);

        JSONObject requstjson = new JSONObject();
        requstjson.put("method", methodName);
        requstjson.put("params", paramArray);
        requstjson.put("id", idGenerator());
        requstjson.put("version", "1.0");

        String requestjson = requstjson.toString();
        System.out.println(requestjson);
        try {

            Response reply = Request.Post(endPointURL(service)).bodyByteArray(requestjson.getBytes()).execute();
            String replyContent = reply.returnContent().asString();
            return new JSONObject(replyContent);

        } catch (IOException iOException) {
            iOException.printStackTrace();
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        return null;
    }

    public static Response httpPostTest(String content) throws IOException {
        Response reply = Request.Put("http://posttestserver.com/post.php").bodyByteArray(content.getBytes())
                .execute();
        System.out.println(reply.returnContent().asString());
        return reply;
    }

    public static String endPointURL(String service) {
        String result = EnvironmentVariables.serviceMap.get(service) + "/" + service;
        //System.out.println(result);
        return result;
    }

    private static int idGenerator() {
        return 1;

    }

}