How to communicate using URLConnection in Java

Your ads will be inserted here by

Easy Plugin for AdSense.

Please go to the plugin admin page to
Paste your ad code OR
Suppress this ad slot.

Reading data with serial communication between Arduino and PC is one step. After the PC has received the data I want it to send the data (raw or after some calculations) to a website. The website will store the data and show the data in some nice graphs and tables.
The other way around I want to send some commands from the website to the PC where the Java app has to send it to the Arduino which on its turn will perform some actions. I will write another post on this subject some other time.

I found a nice page at Oracle describing how to use the Java URLConnection class.

Depending on the functionality of your website script/app you could start very simple with the code below.


import java.io.*;
import java.net.*;

public class Reverse {
    public static void main(String[] args) throws Exception {

	URL url = new URL("http://www.your-domain.nl/store_value.php?type=KAKU&value=1234567");
	URLConnection connection = url.openConnection();
	connection.setDoOutput(true);

	OutputStreamWriter out = new OutputStreamWriter(
                              connection.getOutputStream());
	out.close();

	BufferedReader in = new BufferedReader(
				new InputStreamReader(
				connection.getInputStream()));
	in.close();
    }
}

All we do here is opening an URL to a PHP page and provide it with two variables. These variables can be extracted from the URL by the PHP script. The snippet below shows a piece of PHP code to extract the variables from the URL. After you got the variable values they can be stored in a database, written to a file, etc..

<?php

$type = $_GET['type'];
$value = $_GET['value'];

// store it in a database or write it to a file or ...

print "TYPE = ".$type." -- VALUE =".$value."</BR>"; 

?>

I know it is very basic and not secure in the dangerous open network world (internet), but as a starting point for private network environments it might be helpful.