PeterGriffin
PeterGriffin

Reputation: 910

Sending data from Java to PHP via POST

On one side I have a Java program that keeps feeding a database. On the other a web server (Apache). I need to transfer multiple entries, at once, from the program to a distant web server via a REST webservice. While I have no trouble to send pairs of values from one to the others (using a HttpClient on the Java's side and a PHP file that writes into the server's own database on the other side), I lack knowledge about how I could build my HTTP request with data.

I've been using an Entity so far :

List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("field1", "aaa"));
list.add(new BasicNameValuePair("field2", "bbb"));

httppost.setEntity(new UrlEncodedFormEntity(list));

and receiving it in my PHP file :

<?php
    $field1=$_POST["field1"];
    $field2=$_POST["field2"];
    $con= mysql_connect("localhost","root");
    if(!$con) die("Not able to connect");
    mysql_select_db("mydb",$con);
    mysql_query("INSERT INTO `mytable` (`field1`, `field2`) VALUES ('$field1', '$field2')");
    mysql_close($con);
?>

Works great. Simple and easy. But now, as stated before, I wish to transfer several entries from my database. Each entry consists of 35 fields, which yields to some big data.

My question is : How can I insert my database entries within ONE (or as many as needed if one HTTP request capacity is full) and fetch the resulting data on the PHP file side ? Bonus : with the previous solution, how can I compress that data?

Upvotes: 0

Views: 2201

Answers (2)

ddinchev
ddinchev

Reputation: 34673

Well, the thing you are doing will lead to SQL injection easily. Make sure you escape your data before running the insert query with mysql_real_escape_string or better - prepared statements.

Instead of using JSON, you could use Google Protocol Buffers. You need both JAVA and PHP extension to use protocol buffers but this is binary protocol that compresses the data amazingly well and allows you the flexibility to define different "repeatable" objects (entries) with same properties, so that when you open the protocol buffer on the PHP side, it will be easy to utilize the data.

Upvotes: 1

Ranty
Ranty

Reputation: 3362

You can use JSON for quick and simple transfer. For decoding, PHP supports $array = json_decode($json_string, TRUE);.

Not sure about compressing. Are you going to transfer lots of data this way to make it relevant?

Upvotes: 1

Related Questions