30 September, 2015

ICE4J Networking Part 2 (HTTP Post/Get with Java)
By: Matthew Jackson

Jitsi logoHow do you get your information to the wesite?

Below is some simple code that I wrote that will allow you to take anray where the first index (postParams[i][0]) is the paramater name, the second paramater (postParams[i][1]) is the paramater value. They must both be formatted to strings since that is how the post request is formatted. 

public static String postRequest(String targetURL, String[][] postParams) {
        URL url;
        HttpURLConnection connection = null;
        try {
            // Create connection
            url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            String toPost = formatParams(postParams);
            connection.setRequestProperty("Content-Length", ""
                    + Integer.toString(toPost.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");
 
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.setDoOutput(true);
 
            // Send request
            DataOutputStream wr = new DataOutputStream(connection
                    .getOutputStream());
            wr.writeBytes(toPost);
            wr.flush();
            wr.close();
 
            // Get Response
            InputStream is = connection.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();
            //Retrieve the message
            return response.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

public static String formatParams(String[][] postParams){
        if(postParams==null) return "";        
        StringBuffer out = new StringBuffer();
        for(int i=0; i<postParams.length; i++){
            out.append(postParams[i][0]).append("=").append(postParams[i][1]);
            if((i+1)<postParams.length)
                out.append("&");
        }
        return out.toString();
}

On the other end, your webserver will analyze the post request. PHP is a pretty simple language for this:

$myUsername = $_POST['username'];
if(empty($myUsername)){
  echo("Error: No Username");
}
else {
  echo("Success");
}

That is how you post your data to a webserver and analyze it with PHP. Of course the php code here has to be accessed by a specific url and probably stored in a database, but this isn't the space for a PHP tutorial, and there are TONS out there.

HTTP GET Request

            URL obj = new URL(targetURL);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();     
            con.setRequestMethod("GET");   
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

The above short code is a pretty simple GET request to the targetURL. The bufferedreader you read line by line in a while loop, to get the webservers response.

Tags: ICE4J, Java, Networking