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

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'];

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.

How to send special character via HTTP post request made in Java

I need to send data to another system in a Java aplication via HTTP POST method. Using the Apache HttpClient library is not an option.
I create a URL, httpconection without problems. But when sending special character like Spanish Ñ, the system complains it is receiving
Ñ instead of Ñ.
I've read many post, but I don't understand some things:
When doing a POST connection, and writing to the connection object, is it mandatory to do the URLEncode.encode(data,encoding) to the data being sent?
When sending the data, in some examples I have seen they use the
conn.writeBytes(strData), and in other I have seen conn.write(strData.getBytes(encoding)). Which one is it better? Is it related of using the encode?
Update:
The current code:
URL url = new URL(URLstr);
conn1 = (HttpsURLConnection) url.openConnection();
conn1.setRequestMethod("POST");
conn1.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn1.getOutputStream());
wr.writeBytes(strToSend);//data sent
wr.flush();
wr.close();
(later I get the response)
strToSend has been previously URLENCODE.encode(,"UTF-8")
I still don't know if I must use urlencode in my code and/or setRequestProperty("Contentype","application/x-www-formurlencode");
Or if I must use .write(strToSend.getByte(??)
Any ideas are welcome. I am testing also the real server (I dont know very much about it)

What's the difference between using SoapUI and java code?

I'm using soap to request some information from server.
so, In order to test whether my soap way is the correct way or not, I tested soapUI Pro 4.6.3 program and java code.
when I use soapUI program , I got the response of my request from server. But, when I use java code I couldn't get response of my request from server..
I can see the error code 500. As I know, 500 Error code is Internal Error. so Isn't this problem of server?
I want to know what's the difference between them.
My java code is below.. and The XML code is the same what I use by SoapUI Program and what I use java code.
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("My URL");
int status = 0;
String result = "";
try {
method.setRequestBody(MySoapXML);
method.getParams().setParameter("http.socket.timeout", new Integer(5000));
method.getParams().setParameter("http.protocol.content-charset", "UTF-8");
method.getParams().setParameter("SOAPAction", "My Soap Action URL");
method.getParams().setParameter("Content-Type", MySoapXML.length());
status = client.executeMethod(method);
BufferedReader br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
String readLine;
while ((readLine=br.readLine())!=null) {
System.out.println(readLine);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
and I already did URLConnection Class, and HttpClient Class.. but The result was the same..
If you know the way to solve this problem or have the same experience as me. please let me know how to solve this problem.. thank you for reading ^_^
Soap - UI will parse poorly defined webservices(for eg. Not Well Defined WSDL). From my experience working with SoapUI is not a proof that your webservice is well-defined.

Sending from Java to PHP Scripting

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?

Sending sms via java

I am going to send sms via java. The problem is the sms gateway ask me to send in this format
http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert=
The problem how to call this from a java application is it possible or does it need special libraries? IS it using HttpURLConnection will do the job? Thank you.
A Sample code I have done below is this correct.
URL sendSms1 = new URL("http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert=");
URLConnection smsConn1 =
sendSms1.openConnection();
It's just an HTTP call, you don't need anything special in Java (or any modern language, I expect). Just build up the string as appropriate*, then make an HTTP request to that URL.
Take a peek at the Sun tutorial Reading from and Writing to a URLConnection if you need to pick up the basics of how to do the request part in Java. This uses the built-in classes, I'm sure there are dozens of libraries that handles connections in funky and/or convenient ways too, so by all means use one of those if you're familiar with it.
*One potential gotcha which might not have occurred to you - your query string arguments will have to be URL-encoded. So the + characters for example in the text parameter, are encoded spaces (which would have a different meaning in the URL). Likewise, if you wanted to send a ? character in one of your parameters, it would have to appear as %3F. Have a look at the accepted answer to HTTP URL Address Encoding in Java for an example of how you might build the URL string safely.
It looks like a simple GET request, you can use Apache HttpClient libarary for executing such a request. Have a look into a tutorial by Vogella here: http://www.vogella.de/articles/ApacheHttpClient/article.html for sample source code and explanations.
You can try to use java.net.URL library。
like this
// at this before you need to generate the urlString as "http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert="
URL url = new URL(urlString);
// send sms
URLConnection urlConnection = url.openConnection();// open the url
// and you, also can get the feedback if you want
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
URL url = new URL("http://smscountry.com/SMSCwebservice.asp");
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
[Edit]
urlconnection.setRequestMethod("POST");
urlconnection.setRequestProperty("Content-Type","application/x-www-form-urlenc‌​oded");
urlconnection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(urlconnection.getOutputStream());
out.write(postData);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
retval += decodedString;
}

Categories

Resources