Sending from Java to PHP Scripting - java

first time question. Anyways, I have a bit of a project, basically it has me writing up a GUI using Netbean's GUI builder to get information from a customer and then sending that information into a PHP script. I know that I can get the string from jTextField1.gettext(); and thats well and all, but the problem comes with sending that specific information to the PHP script that will send it to the mySQL database in the group's website.
Java coding for a method that should theoretically work when it's called in the submit action method:
public void Dsend() throws Exception {
URL hp = new URL("http://www.luxuryparking.comeze.com/DBinput.php");
HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();
hpCon.setRequestMethod("POST");
hpCon.setDoOutput(true);
hpCon.setDoInput(true);
// important: get output stream before input stream
PrintStream ps = new PrintStream(hpCon.getOutputStream());
ps.print(jTextField7.getText());
ps.print("secondKey=secondValue;");
// we have to get the input stream in order to actually send the request
hpCon.getInputStream();
// close the print stream
ps.close();
}
PHP Script:
$conn = new PDO("mysql:host=$host;dbname=a4335408_data1", $username, $password);
foreach ($_POST as $key => $value) {
switch ($key) {
case 'license':
$license = $value;
break;
default:
break;
}
}
$license='1234567';
$sql = "INSERT INTO Reservation (LicensePlate) VALUES (:license)";
$q = $conn->prepare($sql);
$q->execute(array(':license'=>$license));
Thank you for the help!

$q->execute(array(':license'=>$license));
should be
$q->execute(array('license'=>$license));
On the Java side doInput(false) without getInputStream seems more appropiate. Apache's HttpClient might be a more helpful API.

In the java procedure, data sent to server should be formatted in "application/x-www-form-urlencoded".
See also: How to use HttpURLConnection POST data to web server?

Related

What is the correct URL for Google's Cloud Speech API internet requests and how to request using java?

I'm simply using Eclipse IDE and Java to try to collect voice memos through a microphone, then turn that audio into text in real time. I'm not sure if I'm doing it right but if I send this URL the compiler give me a 403 error meaning it doesn't accept the key that I paste onto the URL. So my question is:
Does anyone happen to know why the URL connection is not taking my key? or which application restriction should I be using instead of NONE?
public class Recognizer {
/**
* URL to POST audio data and retrieve results
*/
private static final
String GOOGLE_RECOGNIZER_URL_NO_LANG
= "http://www.google.com/speech-api/v2/recognize?lang=en-
us&key=InsertMyKey&output=json";
. . .
. . .
. . .
private String rawRequest(byte[] bytes, String language) throws Exception {
System.out.println("in this second construct" );
URL url;
URLConnection urlConn;
OutputStream outputStream;
BufferedReader br;
// URL of Remote Script.
url = new URL(GOOGLE_RECOGNIZER_URL_NO_LANG);
// Open New URL connection channel.
urlConn = url.openConnection();
// we want to do output.
urlConn.setDoOutput(true);
// No caching
urlConn.setUseCaches(false);
// Specify the header content type.
urlConn.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");
// Send POST output.
outputStream = urlConn.getOutputStream();
outputStream.write(bytes);
outputStream.close();
// Get response data.
br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String response = br.readLine();
br.close();
return response;
}
picture of my key settings
This API endpoint release seems to be offered only for the community developers of the Chromium project; however, it is NOT possible to get additional quota, as mentioned in this documentation.
Instead, it is required to use the official v1 or v1p1beta1 endpoints to perform you speech recognition tasks. Additionally, I recommend you to take a look on the Client Libraries guides in order to get detailed information about the process to use Speech-to-Text API service by using programming languages, including Java.

Return collection from php script to my android app

I am wondering if there is a way to return a mongo collection from php script to java. Lets say that i am connecting to url in my Android application like this:
URL url = new URL(SERVER_ADDRESS + "db.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
where db.php is this:
$db = new Mongo('mongodb://.../test');
$c_things = $db->things;
where $c_things is the collection.
Could i retrieve/parse $c_things in my app as MongoCollection<Document> format? If there is a tutorial out there is very welcome.
Use bson_encode on the php side to generate a BSON string and return that. And then on the Java side user he mongo DB BSON decode function to turn it back into a collection.
The best practice to do that is with JSONArray try return that from Server and use Retrofit to consuming the service properly.

Post with Java to PHP sending parameters and read parameters from PHP

I know that there are many questions related to this, but I have a special scenario and I'm here to know if somebody could help me with it, I have an approach to what is required, so let me describe the scenario first:
I have a PHP which is a kind of proxy, it will receives requests from some client, in my case a Java class using HttpUrlConnection. As soon as this PHP receives the connection (request), the php will extract the parameters sent by the client, in my case, the parameters are: an id (String) and an xml (as String). So, as soon as my java client sends the request, my php "proxy" catch it and extract the parameters, because my php is like an "intermediate" component which redirects the requests to another place using curl, but this specific php which receives the request needs to extract de id and the xml. From java, I am using:
URL calledUrl = new URL(phpUrl);
URLConnection phpConnection = calledUrl.openConnection();
HttpURLConnection httpBasedConnection = (HttpURLConnection) phpConnection;
httpBasedConnection.setRequestMethod("POST");
httpBasedConnection.setDoOutput(true);
StringBuffer paramsBuilder = new StringBuffer();
paramsBuilder.append("xmlQuery=");
paramsBuilder.append(URLEncoder.encode(this.xmlQuery, CHARSET));
paramsBuilder.append("&ids=");
paramsBuilder.append(URLEncoder.encode("16534", CHARSET));
PrintWriter requestWriter = new PrintWriter(httpBasedConnection.getOutputStream(), true);
requestWriter.print(paramsBuilder.toString());
requestWriter.close();
BufferedReader responseReader = new BufferedReader(new InputStreamReader(
phpConnection.getInputStream()));
String receivedLine;
StringBuffer responseAppender = new StringBuffer();
while ((receivedLine = responseReader.readLine()) != null ) {
responseAppender.append(receivedLine);
responseAppender.append("\n");
}
responseReader.close();
result = responseAppender.toString();
As you can see, I am sending the parameters and waiting for a response (which is an echo).
For my php, I have the following:
$rawdata = file_get_contents('php://input');
$rawXml = simplexml_load_file('php://input');
I don't know if this is ok, but I saw a tutorial about receiving requests and these lines were there. I want to get the data from the post that my java executes and then work with them as strings in my php.
If somebody could help me, I will really appreciate it. Thanks in advance, any help is welcome.
You would want to use this in PHP:
$id = $_POST['id'];
$xml = $_POST['xmlQuery'];

Send data from android to php

I need to help about to send data from android to php. I have this java code for android;
public void sendToDb()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("pLat",Double.toString(lat)));
nameValuePairs.add(new BasicNameValuePair("pLng",Double.toString(lng)));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://123456.com/welcome.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
and I have in my php folder this codes;
<?php
$pLat = $_POST['pLat'];
$pLng = $_POST['pLng'];
$result = mysql_query("update Users set lat='$pLat',lon='$pLng' where username='ozi');
if (mysql_affected_rows()==0)
{
$query = "INSERT INTO Users ";
$query .= "(lat,lon) VALUES ('$pLat','$pLng')";
}
}
?>
When I send to data from my phone there is no problem but after I look mysql lat and lot rows not null but empty.
Is there a problem that you see in codes?
After reading your comments, what you're trying to do (I think) is persist data. The php file does nothing but run the code you have. The POST variables are only alive if you pass them in the request. The request is coming from the Android app along with POST variables and the response to the Android app will have the correct output.
The request coming from your browser is a "GET" and does not send a pLat or pLng variable, so there is no variables to output.
This is a very basic concept of HTTP that you must grasp.
What you are trying to do is save the data somewhere. PHP can do that by saving it to a database (such as MySQL) or by simply outputting the POST variables to a local file. A quick google search can show you how to save files and open databases. Heck, you can even just send them in an email to yourself.
The PHP script will only hold those variables for the life of the script and then release them out of memory forever. It's up to you to use the power of PHP to save those variables somewhere else.
At a glance I can already see some insanity here. Why do you specify where username= { $_SESSION['username']} when the call is coming from an android device? What session is there? Additionally, if this fails you insert with no username. but then never run the query.
if (mysql_affected_rows()==0)
{
$query = "INSERT INTO Users ";
$query .= "(username, lat,lon) VALUES ('ozi', '$pLat','$pLng')";
mysql_query($query) or die(mysql_error()); // <---- this would need to be run
}
}
I suggest you fix those 2 very critical observations first, then update your question with a more targeted problem. Then I may update this answer to be more useful.

Java: how to send POST request while displaying the page?

Here is my code:
try
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "png", os);
byte[] bytes = os.toByteArray();
os.flush();
os.close();
String code = encode(bytes);
URL base = applet.getCodeBase();
URL url = new URL(base.getProtocol(),
base.getHost(),
base.getPort(),
"/image.php?code=" + code);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
c.setDoOutput(true);
DataOutputStream s = new DataOutputStream(c.getOutputStream());
s.writeBytes("code=" + code);
applet.getAppletContext().showDocument(url, "_blank");
}
catch (Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(
this,
e.toString(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
By the time I use showDocument, the POST request is already done, so what I'm really doing is showing a blank page (instead, I want to show the image). The source of image.php is this:
<?php
$code = base64_decode($_GET["code"]);
header('Content-Type: image/png');
echo $code;
?>
You are using POST on Java and GET on PHP...
Your showDocument and the applet's POST request are completely independent. The POST request is done by your applet, and the result would be only usable inside your applet (but you are not reading it at all - and I'm not sure it is even sent).
showDocument, in contrast, always does a GET request - there is no way to instruct the browser to use POST here. You might be able to fabricate a POST request for a new HTML page by using the JavaScript bridge from your applet, though.
Theoretically, it should work anyways, as you send the image data as part of the URL, too, but there might be a length limit for the URL data in the Web server, or in the link from Java-Plugin to the browser.
You could instead encode your image in a data: URL, and use this for showDocument.
URL url = new URL("data:image/png;base64," + code);
(I did not test if Java's URL class actually accepts this. Please try and report. I suppose it is subject to the same browser URL length limits.)
An alternative would be having the server store the image (at least for some short time). Then you would use your POST from the applet to upload the data, get back (short) some unique identifier, which you then would pass to the showDocument URL.

Categories

Resources