Android Question Sony Camera API

stu14t

Active Member
Licensed User
Longtime User
First of all I'll give a bit of background here:

I work in Highway maintenance and have written various little apps to help me on a day to day basis. My next task I've given myself is to write an app to control new video cameras we have just purchased.

We use video a lot. It's often safer than running about a motorway, or any road for that matter. What we currently do is, using a HD camcorder and a sub-meter accurate GPS system we can work out the gps position of every frame, so locate assets and defects in the frame. At the moment it's not very accurate. The GPS gives a position every second and sync the two by recording the GPS display at the start of the survey showing the GPS time. We have now purchased two new camcorders with built in GPS. Now, we don't use the camcorder GPS for position, it's not good enough, but for the time synchronization. That only gives us per second accuracy for position and if you're traveling at traffic speed, you will cover over 20m.

The app I'm looking into trying to build uses Sony's API to control the start/ stop of the filming. I can sync the android device to GPS / UTC time using various apps and then record the time of starting the video down to milliseconds. I know there will be a lag but it's got to be better that what we do at the moment.

I have never delved into using API's, HTTP or JSON it's all new to me but I've made an attempt to look over the SDK provided by Sony (Attached)

Here's my question: looking at the code provided I'm not sure if a wrapper library is required or if you can get away with just using Httputils2 and JSON? There is a discussion about SSDP-M Search and UPnP, which i'm not too sure about.

Is is a matter of sending the requests detailed and parsing the responses from the camera to get the references for the API? Just a little guidance would be helpful.

The documentation and some sample code can be downloaded HERE
 

stu14t

Active Member
Licensed User
Longtime User
Communicating with the camera with JSON should be quite simple.
The search step is a bit more complicated (maybe you can skip it?). You will need to use the Network library to implement the protocol which is based on UDP communication.

I've looked at some of the code examples and wonder if this could be turned into a library?

B4X:
/*
* Copyright 2013 Sony Corporation
*/

package com.example.sony.cameraremote;

import android.util.Log;

import com.example.sony.cameraremote.ServerDevice.ApiService;
import com.example.sony.cameraremote.utils.SimpleHttpClient;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

/**
* Simple Camera Remote API wrapper class. (JSON based API <--> Java API)
*/
public class SimpleRemoteApi {

    private static final String TAG = SimpleRemoteApi.class.getSimpleName();

    // If you'd like to suppress detailed log output, change this value into
    // false.
    private static final boolean FULL_LOG = true;

    // API server device you want to send requests.
    private ServerDevice mTargetServer;

    // Request ID of API calling. This will be counted up by each API calling.
    private int mRequestId;

    /**
    * Constructor.
    *
    * @param target server device of Remote API
    */
    public SimpleRemoteApi(ServerDevice target) {
        mTargetServer = target;
        mRequestId = 1;
    }

    // Retrieves Action List URL from Server information.
    private String findActionListUrl(String service) {
        List<ApiService> services = mTargetServer.getApiServices();
        for (ApiService apiService : services) {
            if (apiService.getName().equals(service)) {
                return apiService.getActionListUrl();
            }
        }
        throw new IllegalStateException("actionUrl not found.");
    }

    // Request ID. Counted up after calling.
    private int id() {
        return mRequestId++;
    }

    // Output a log line.
    private void log(String msg) {
        if (FULL_LOG) {
            Log.d(TAG, msg);
        }
    }

    // Camera Service APIs

    /**
    * Calls getAvailableApiList API to the target server. Request JSON data is
    * such like as below.
    *
    * <pre>
    * {
    *  "method": "getAvailableApiList",
    *  "params": [""],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject getAvailableApiList() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "getAvailableApiList")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls getApplicationInfo API to the target server. Request JSON data is
    * such like as below.
    *
    * <pre>
    * {
    *  "method": "getApplicationInfo",
    *  "params": [""],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject getApplicationInfo() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "getApplicationInfo")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls getShootMode API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "getShootMode",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject getShootMode() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "getShootMode")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls setShootMode API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "setShootMode",
    *  "params": ["still"],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @param shootMode shoot mode (ex. "still")
    * @return JSON data of response
    */
    public JSONObject setShootMode(String shootMode) throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "setShootMode")
                    .put("params", new JSONArray().put(shootMode))
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls getAvailableShootMode API to the target server. Request JSON data
    * is such like as below.
    *
    * <pre>
    * {
    *  "method": "getAvailableShootMode",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject getAvailableShootMode() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "getAvailableShootMode")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls getSupportedShootMode API to the target server. Request JSON data
    * is such like as below.
    *
    * <pre>
    * {
    *  "method": "getSupportedShootMode",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject getSupportedShootMode() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "getSupportedShootMode")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls startLiveview API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "startLiveview",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject startLiveview() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "startLiveview")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls stopLiveview API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "stopLiveview",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject stopLiveview() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "stopLiveview")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls startRecMode API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "startRecMode",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject startRecMode() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "startRecMode")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls stopRecMode API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "stopRecMode",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject stopRecMode() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "stopRecMode")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls actTakePicture API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "actTakePicture",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject actTakePicture() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "actTakePicture")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls startMovieRec API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "startMovieRec",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject startMovieRec() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "startMovieRec")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls stopMovieRec API to the target server. Request JSON data is such
    * like as below.
    *
    * <pre>
    * {
    *  "method": "stopMovieRec",
    *  "params": [],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject stopMovieRec() throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "stopMovieRec")
                    .put("params", new JSONArray())
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls actZoom API to the target server. Request JSON data is such like as
    * below.
    *
    * <pre>
    * {
    *  "method": "actZoom",
    *  "params": ["in","stop"],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @return JSON data of response
    */
    public JSONObject actZoom(String direction, String movement) throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject()
                    .put("method", "actZoom")
                    .put("params", new JSONArray().put(direction).put(movement))
                    .put("id", id())
                    .put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString());
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }

    /**
    * Calls getEvent API to the target server. Request JSON data is such like
    * as below.
    *
    * <pre>
    * {
    *  "method": "getEvent",
    *  "params": [true],
    *  "id": 2,
    *  "version": "1.0"
    * }
    * </pre>
    *
    * @param longPollingFlag true means long polling request.
    * @return JSON data of response
    */
    public JSONObject getEvent(boolean longPollingFlag) throws IOException {
        String service = "camera";
        try {
            JSONObject requestJson = new JSONObject().put("method", "getEvent")
                    .put("params", new JSONArray().put(longPollingFlag))
                    .put("id", id()).put("version", "1.0");
            String url = findActionListUrl(service) + "/" + service;
            int longPollingTimeout = (longPollingFlag) ? 20000 : 8000; // msec

            log("Request:  " + requestJson.toString());
            String responseJson = SimpleHttpClient.httpPost(url,
                    requestJson.toString(), longPollingTimeout);
            log("Response: " + responseJson);
            return new JSONObject(responseJson);
        } catch (JSONException e) {
            throw new IOException(e);
        }
    }
}
 
Upvote 0

stu14t

Active Member
Licensed User
Longtime User
Communicating with the camera with JSON should be quite simple.
The search step is a bit more complicated (maybe you can skip it?). You will need to use the Network library to implement the protocol which is based on UDP communication.

I think this is the JAVA code for the search step:

B4X:
/*
* Copyright 2013 Sony Corporation
*/

package com.example.sony.cameraremote.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;

/**
* Simple HTTP Client for sample application.
*/
public class SimpleHttpClient {

    private static final String TAG = SimpleHttpClient.class.getSimpleName();

    private static final int DEFAULT_CONNECTION_TIMEOUT = 10000; // [msec]
    private static final int DEFAULT_READ_TIMEOUT = 10000; // [msec]

    /**
    * Send HTTP GET request to the indicated url. Then returns response as
    * string.
    *
    * @param url request target
    * @return response as string
    * @throws IOException all errors and exception are wrapped by this
    *            Exception.
    */
    public static String httpGet(String url) throws IOException {
        return httpGet(url, DEFAULT_READ_TIMEOUT);
    }

    /**
    * Send HTTP GET request to the indicated url. Then returns response as
    * string.
    *
    * @param url request target
    * @param timeout Request timeout
    * @return response as string
    * @throws IOException all errors and exception are wrapped by this
    *            Exception.
    */
    public static String httpGet(String url, int timeout) throws IOException {
        HttpURLConnection httpConn = null;
        InputStream inputStream = null;

        // Open connection and input stream
        try {
            final URL _url = new URL(url);
            httpConn = (HttpURLConnection) _url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);
            httpConn.setReadTimeout(timeout);
            httpConn.connect();

            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
            if (inputStream == null) {
                Log.w(TAG, "httpGet: Response Code Error: " + responseCode
                        + ": " + url);
                throw new IOException("Response Error:" + responseCode);
            }
        } catch (final SocketTimeoutException e) {
            Log.w(TAG, "httpGet: Timeout: " + url);
            throw new IOException();
        } catch (final MalformedURLException e) {
            Log.w(TAG, "httpGet: MalformedUrlException: " + url);
            throw new IOException();
        } catch (final IOException e) {
            Log.w(TAG, "httpGet: " + e.getMessage());
            if (httpConn != null) {
                httpConn.disconnect();
            }
            throw e;
        }

        // Read stream as String
        BufferedReader reader = null;
        try {
            StringBuilder responseBuf = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            int c;
            while ((c = reader.read()) != -1) {
                responseBuf.append((char) c);
            }
            return responseBuf.toString();
        } catch (IOException e) {
            Log.w(TAG, "httpGet: read error: " + e.getMessage());
            throw e;
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing BufferedReader");
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing InputStream");
            }
        }
    }

    /**
    * Send HTTP POST request to the indicated url. Then returns response as
    * string.
    *
    * @param url request target
    * @param postData POST body data as string (ex. JSON)
    * @return response as string
    * @throws IOException all errors and exception are wrapped by this
    *            Exception.
    */
    public static String httpPost(String url, String postData)
            throws IOException {
        return httpPost(url, postData, DEFAULT_READ_TIMEOUT);
    }

    /**
    * Send HTTP POST request to the indicated url. Then returns response as
    * string.
    *
    * @param url request target
    * @param postData POST body data as string (ex. JSON)
    * @param timeout Request timeout
    * @return response as string
    * @throws IOException all errors and exception are wrapped by this
    *            Exception.
    */
    public static String httpPost(String url, String postData, int timeout)
            throws IOException {
        HttpURLConnection httpConn = null;
        OutputStream outputStream = null;
        OutputStreamWriter writer = null;
        InputStream inputStream = null;

        // Open connection and input stream
        try {
            final URL _url = new URL(url);
            httpConn = (HttpURLConnection) _url.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);
            httpConn.setReadTimeout(timeout);
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

            outputStream = httpConn.getOutputStream();
            writer = new OutputStreamWriter(outputStream, "UTF-8");
            writer.write(postData);
            writer.flush();
            writer.close();
            writer = null;
            outputStream.close();
            outputStream = null;

            httpConn.connect();
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
            if (inputStream == null) {
                Log.w(TAG, "httpPost: Response Code Error: " + responseCode
                        + ": " + url);
                throw new IOException("Response Error:" + responseCode);
            }
        } catch (final SocketTimeoutException e) {
            Log.w(TAG, "httpPost: Timeout: " + url);
            throw new IOException();
        } catch (final MalformedURLException e) {
            Log.w(TAG, "httpPost: MalformedUrlException: " + url);
            throw new IOException();
        } catch (final IOException e) {
            Log.w(TAG, "httpPost: IOException: " + e.getMessage());
            if (httpConn != null) {
                httpConn.disconnect();
            }
            throw e;
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing OutputStreamWriter");
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing OutputStream");
            }
        }

        // Read stream as String
        BufferedReader reader = null;
        try {
            StringBuilder responseBuf = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(inputStream));

            int c;
            while ((c = reader.read()) != -1) {
                responseBuf.append((char) c);
            }
            return responseBuf.toString();
        } catch (IOException e) {
            Log.w(TAG, "httpPost: read error: " + e.getMessage());
            throw e;
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing BufferedReader");
            }
        }
    }
}
 
Upvote 0

wy328

Member
Licensed User
Longtime User
I think this is the JAVA code for the search step:

B4X:
/*
* Copyright 2013 Sony Corporation
*/

package com.example.sony.cameraremote.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;

/**
* Simple HTTP Client for sample application.
*/
public class SimpleHttpClient {

    private static final String TAG = SimpleHttpClient.class.getSimpleName();

    private static final int DEFAULT_CONNECTION_TIMEOUT = 10000; // [msec]
    private static final int DEFAULT_READ_TIMEOUT = 10000; // [msec]

    /**
    * Send HTTP GET request to the indicated url. Then returns response as
    * string.
    *
    * @param url request target
    * @return response as string
    * @throws IOException all errors and exception are wrapped by this
    *            Exception.
    */
    public static String httpGet(String url) throws IOException {
        return httpGet(url, DEFAULT_READ_TIMEOUT);
    }

    /**
    * Send HTTP GET request to the indicated url. Then returns response as
    * string.
    *
    * @param url request target
    * @param timeout Request timeout
    * @return response as string
    * @throws IOException all errors and exception are wrapped by this
    *            Exception.
    */
    public static String httpGet(String url, int timeout) throws IOException {
        HttpURLConnection httpConn = null;
        InputStream inputStream = null;

        // Open connection and input stream
        try {
            final URL _url = new URL(url);
            httpConn = (HttpURLConnection) _url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);
            httpConn.setReadTimeout(timeout);
            httpConn.connect();

            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
            if (inputStream == null) {
                Log.w(TAG, "httpGet: Response Code Error: " + responseCode
                        + ": " + url);
                throw new IOException("Response Error:" + responseCode);
            }
        } catch (final SocketTimeoutException e) {
            Log.w(TAG, "httpGet: Timeout: " + url);
            throw new IOException();
        } catch (final MalformedURLException e) {
            Log.w(TAG, "httpGet: MalformedUrlException: " + url);
            throw new IOException();
        } catch (final IOException e) {
            Log.w(TAG, "httpGet: " + e.getMessage());
            if (httpConn != null) {
                httpConn.disconnect();
            }
            throw e;
        }

        // Read stream as String
        BufferedReader reader = null;
        try {
            StringBuilder responseBuf = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(inputStream));
            int c;
            while ((c = reader.read()) != -1) {
                responseBuf.append((char) c);
            }
            return responseBuf.toString();
        } catch (IOException e) {
            Log.w(TAG, "httpGet: read error: " + e.getMessage());
            throw e;
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing BufferedReader");
            }
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing InputStream");
            }
        }
    }

    /**
    * Send HTTP POST request to the indicated url. Then returns response as
    * string.
    *
    * @param url request target
    * @param postData POST body data as string (ex. JSON)
    * @return response as string
    * @throws IOException all errors and exception are wrapped by this
    *            Exception.
    */
    public static String httpPost(String url, String postData)
            throws IOException {
        return httpPost(url, postData, DEFAULT_READ_TIMEOUT);
    }

    /**
    * Send HTTP POST request to the indicated url. Then returns response as
    * string.
    *
    * @param url request target
    * @param postData POST body data as string (ex. JSON)
    * @param timeout Request timeout
    * @return response as string
    * @throws IOException all errors and exception are wrapped by this
    *            Exception.
    */
    public static String httpPost(String url, String postData, int timeout)
            throws IOException {
        HttpURLConnection httpConn = null;
        OutputStream outputStream = null;
        OutputStreamWriter writer = null;
        InputStream inputStream = null;

        // Open connection and input stream
        try {
            final URL _url = new URL(url);
            httpConn = (HttpURLConnection) _url.openConnection();
            httpConn.setRequestMethod("POST");
            httpConn.setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT);
            httpConn.setReadTimeout(timeout);
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);

            outputStream = httpConn.getOutputStream();
            writer = new OutputStreamWriter(outputStream, "UTF-8");
            writer.write(postData);
            writer.flush();
            writer.close();
            writer = null;
            outputStream.close();
            outputStream = null;

            httpConn.connect();
            int responseCode = httpConn.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inputStream = httpConn.getInputStream();
            }
            if (inputStream == null) {
                Log.w(TAG, "httpPost: Response Code Error: " + responseCode
                        + ": " + url);
                throw new IOException("Response Error:" + responseCode);
            }
        } catch (final SocketTimeoutException e) {
            Log.w(TAG, "httpPost: Timeout: " + url);
            throw new IOException();
        } catch (final MalformedURLException e) {
            Log.w(TAG, "httpPost: MalformedUrlException: " + url);
            throw new IOException();
        } catch (final IOException e) {
            Log.w(TAG, "httpPost: IOException: " + e.getMessage());
            if (httpConn != null) {
                httpConn.disconnect();
            }
            throw e;
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing OutputStreamWriter");
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing OutputStream");
            }
        }

        // Read stream as String
        BufferedReader reader = null;
        try {
            StringBuilder responseBuf = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(inputStream));

            int c;
            while ((c = reader.read()) != -1) {
                responseBuf.append((char) c);
            }
            return responseBuf.toString();
        } catch (IOException e) {
            Log.w(TAG, "httpPost: read error: " + e.getMessage());
            throw e;
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                Log.w(TAG, "IOException while closing BufferedReader");
            }
        }
    }
}

I want to make a remote app for Sony cameras. How's your work? Could you share more information or libs? Thanks!
 
Upvote 0

stu14t

Active Member
Licensed User
Longtime User
I want to make a remote app for Sony cameras. How's your work? Could you share more information or libs? Thanks!

As Erel has already said, this could be implemented without any specific libs, just the Network lib is required.

I've only just ordered the cameras and I'm going to start messing as soon as they arrive. Most of what you need is in the link provided in the first post and then all you need to do is convert the JAVA routines into B4A.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
This is a community forum. We are here to HELP YOU learning b4a. We are not here to write the code you need for you.
 
Upvote 0

mindcom

Member
Licensed User
Longtime User
Dear stu14t, have you some progress on your work with sony camera? I work in Switzerland in similar tasks you have described.
 
Upvote 0

stu14t

Active Member
Licensed User
Longtime User
This one's gone on the back burner at the moment. I purchased the wifi adapters for the cameras but never received them (long story).

However, looking at the Httputils2 it should be fairly simple to send and receive the JSON requests needed

I'll keep you up to date when I start working on this

Stuart
 
Upvote 0

mindcom

Member
Licensed User
Longtime User
Thank you Stuart,
I have a Sony QX10 and I think that I'll try someting with httputils within next week.
I'll keep you informed as well.

Andrea
 
Upvote 0
Top