I'm trying to make communication between PHP and Java.
Here's what I want to do.
PHP pass a parameter ID to a Java file.
The Java get the ID and run some script and return a, ARRAY to the PHP.
I have read out a lot such as PHP/Java Bridge, SOAP, RestCall ...
But I couldn't found out one which works. basically is I don't know how to configure.
I want to find some simple examples which I can understand. And I don't need to use PHP/Java Bridge.
Something easier would do.
Update.
*I had tried Curl call to the Java file, on the $result = curl_exec($curl) returns the entire CODE in the Java.*
I even try Java Servlet, it also return only the entire CODE in the Java.
What I want is PHP make a GET request to the Java, Java will detect the GET request and obtain a parameter ID. Run some process and return an ARRAY back to the PHP.
I want it to be done in a HTTP request only.
But I couldn't figure out how it works. I even tried the HTTPComponent.
Please help out and show me simple example in the PHP and Java file.
I even follow this servlet http://brajeshwar.com/2008/handling-http-get-requests-in-java-servlets/
CGI http://www.javaworld.com/jw-01-1997/jw-01-cgiscripts.html?page=3
, and not only these. A lot examples. But none work.
Did I miss out anything? I will provide more details. I used XAMPP, every project and file will be in my htdocs.
All request will be something like this "http: // localhost/test/...."
Thank you.
Sorry that I didn't stated clearly enough.
The JAVA file is the normal JAVA file such as
public class HelloWorld {
String hw = "Hello World";
public void getHelloWorld() {
System.out.println("abc");
}
public static void main(String [] args){
System.out.println("abc");
}
}
Thank you.
Update 2
Here's my next question.
Like those Curl, Rest, Cgi call.. Its actually called to the .Java file right?
And the result return is the Entire source code of the .Java.
This is because there's no compiler to compile the Java class right?
I put the Java file in the xampp/htdocs, I compile it using Netbeans.
So when I call from PHP, there's no one to compile it?
Correct me if I'm wrong?
So I should put the .Java file in a server such as Tomcat right? Or ways to compile it?
I tried to put in the tomcat webapps, and connect to it through localhost:8080/test/test.java
It return me error 404.
How to access to .Java fil using Web Browser?
Please help me.
Thank you.
SOLVED
Works Java with RESTFul.
And I can get Curl call to Java.
Follow this guide
Very clear for beginners in Java like me.
I would advice you to read up on Spring MVC and create a REST full webservice. Calling an executable java class might work to ofcourse, but I do believe that isn't common practice.
Here is an example of a possible controller class to call.
#Controller
public class TestController extends BaseController {
#RequestMapping(value = "/rest/helloworld", method = RequestMethod.GET)
public #ResponseBody
String helloWorld(HttpServletRequest req)
throws Exception {
return "hello world";
}
}
This is pretty advanced java though especially if you want to configure it all in Spring. I can't explain all of this in detail in this little post. However this site might enlighten you more http://viralpatel.net/blogs/tutorial-spring-3-mvc-introduction-spring-mvc-framework/ .
Try the exmple of Rest
<?php
$url = 'JAVA_PAGE_URL';
// Open a curl session for making the call
$curl = curl_init($url);
// Tell curl to use HTTP POST
curl_setopt($curl, CURLOPT_POST, true);
// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// Set the POST arguments to pass to the Sugar server
$parameters = array('id'=>$id);
$json = json_encode($parameters);
$postArgs = 'method=login&input_type=JSON&response_type=JSON&rest_data=' . $json;
curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
// Make the REST call, returning the result
$response = curl_exec($curl);
// Close the connection
curl_close($curl);
// Convert the result from JSON format to a PHP array
$result = json_decode($response);
?>
I hope this will give you some better ideas to use cURL() for RESTFul webservices .
$curl = curl_init();
$url = "http:";
$fields = 8;
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//To use https
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($fields));
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($curl, CURLOPT_COOKIEFILE, "cookie.txt");
$curl_response = curl_exec($curl);
u can manipulate the $curl_reponse in php.
Related
I'm recieving 'null' on my Params.
So far i've found people using "PathParams", "FormParams" and "QueryParams" on java to get their variables from the request, however in my case, using post i dont have PathParams, and for some reason FormParams and QueryParams are returning null as if i had never sent them. So i'd like help to solve this.
My php cURL POST request:
<?php
$url = "http://localhost:8080/TestRest/test/asd";
$params = "param1=val1¶m2=val2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>
My java Web Service:
#Path("/test")
public class Streams {
#POST
#Path("/asd")
#Produces(MediaType.TEXT_PLAIN)
#Consumes({"application/x-www-form-urlencoded"})
public String addStream(#FormParam("param1") String param1,
#FormParam("param2") String param2) {
return "param1 = "+param1;
}
}
For some reason param1 is null.
What am i doing wrong?
I am going out on a limb and saying your problem may stem from this:
urlencode($params);
For instance: a=1&b=2&c=3 is perfectly valid.
urlencode('a=1&b=2&c=3') goes to this: a%3D1%26b%3D2%26c%3D3 and your webservice may not understand what it is your are passing. It is looking for a=...&b=...&c=... and you are not giving it any of that.
Try leaving off the urlencode() and seeing if it works. If it does, and you still want to ensure content like this&this is encoded properly, then you will need to parse the url parameters, encode them, and then recombine them for the post data.
I know there are a lot of questions related to this issue, but I'm facing an specific requirement for this purpose of posting data from PHP to a Rest Web Service. The details are explained above, but in summary, when I post data to a url (REST WS) and set the CURLOPT_POSTFIELDS the data is not being added to the request.
The scenario: I have a lot of Java Web Services (REST) running as modules, for example, I have a fileUploadModule which is a REST, I have a databaseModule which is another rest and finally a SearchModule, which is another REST.
I can invoke them directly my rest modules using a link like:
http://[MY IP]:8020/system.file.ws.module.ModuleFile/getResults/jsonp?fileName=fileName
http://[MY IP]:8021/system.search.ws.module.ModuleSearch/getResults/jsonp?xmlQuery=myXml
For the case of files and database, the programmer that was managing the code before me used gwt that connected to the module through a proxy; for instance:
http://[MY_PROXY_IP]:8013/system.file.ws.module.ModuleFile/getResults/jsonp?fileName=fileName
and in my proxy I can print the value of the request received, in this case I use a GET and I can print the request as:
GET /system.file.ws.module.ModuleFile/getResults/jsonp?fileName=idc1&folderType=campaign&callback=__gwt_jsonp__.P0.onSuccess&failureCallback=__gwt_jsonp__.P0.onFailure HTTP/1.1
. Now I am responsible for search that should run through PHP. I tested the url directly to the module and it works, but if I try to it by a proxy it does not seems to be working, it reach my proxy but when I print the request it is incomplete:
POST /system.search.ws.module.ModuleSearch/getResults HTTP/1.1
and I am supposed to receive something like the module file, I share my php code, all seems to be ok, but I don't know what can I be doing wrong... when I set the parameters in CURLOPT_POSTFIELDS the string is not being set
$url = "http://192.168.3.41:8013/system.search.ws.module.ModuleSearch/getResults";
try {
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
$rawXml = $_POST['rawXml'];
$rawXml = str_replace("%", "%25", $rawXml);
$rawXml = str_replace("&", "%26", $rawXml);
$rawXml = str_replace("=", "%3D", $rawXml);
echo $rawXml;
curl_setopt ($ch, CURLOPT_POSTFIELDS,'xmlQuery='.$rawXml);
$info = curl_exec ($ch);
curl_close ($ch);
echo $info;
} catch (Exception $e){
echo $e->getMessage();
}
please I would really appreciate your help or observations. Than you very much in advance.
After long time, I saw this without an answer. I discovered the fail of this some time ago. This issue occurred because, when reaching server side, for some reason a batch file I did not noiced was adding an additional line to my content, and whenever I read the request content with my proxies, I used a "\n" delimiter, I mean, I have been reading my data using as the EOF indicator a line jump, that's why the content was never shown. I had to modify the code inside my proxy to allow reading the request until the end, not when finding a "\n" character. I mean, the content of the post was set in every case, but a batch process was corrupting that data. So thata was the issue, I just solved it by making sure that my reader always read my entire file considering even line jumps and white lines.
Regards.
I've been tasked to translate an api from php to java.
The problem is when I have to call to the Api, it uses the curl library, which I don't even know that well in php, and I'm having a hard time finding its equivalent java.
Looking through other post I saw that most people recommended to use httpConnection, but still I can't figure it out.
any help would be apreciated:
$ch = curl_init( $curlUrl );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, true););
if (strtolower($this->httpmethod) == "post") curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
$this->output = curl_exec($ch);
curl_close($ch);
Thank you.
The standard entry point to HTTP requests in Java is java.net.URL. From there you can open a connection to the URL.
I am porting a php snippet that relies on cookiejar provided by curl to get cookie and use it in the subsequent calls. I am facing problem with implementing the same code in Java with Apache Camel. I am not able to read the cookie that is returned. Any suggestions?
The php snippet is below:
$ckfile = tempnam ("/tmp", "CURLCOOKIE");
....
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// Executing the ch
$result['EXE'] = curl_exec($ch);
$result['INF'] = curl_getinfo($ch);
$result['ERR'] = curl_error($ch);
//print_r($result['EXE']);
Its a bit poor description of the problem you do. With only the PHP code. And no information about which Camel version, and what you do in Camel etc.
For what it is worth, the cookies ought to be stored as headers in the Camel message.
I have a Java application that I need to integrate our existing PHP website with. The vendor wants us to do a server-side redirect to allow for secure authentication and single-sign-on, but I'm not sure how to do that in PHP. The vendor explained the workflow as follows:
User clicks on a 'Open Application' link on our PHP site
The PHP application hits a page on the Java application, sending the authentication parameters
If successful, the PHP application sends the headers back to the user's browser, which forces a 'redirect', otherwise the PHP app displays an error
What this will allow would be for our PHP app to securely talk to the Java app, and the client never has to send any sort of authentication.
From what I understand, .NET and Java have this capability built in, but I can't find a way in PHP to do this. Any ideas?
UPDATE
I'm not talking about using the header("Location: ..."); function to do a redirect. The kicker with this server-side redirect is that the app does the authentication and sends all that information back to the client so that the client is then logged in. Using header("Location: ...") just forces the browser to go elsewhere.
UPDATE 2
autologin.php (Simulates the user logging into an external app via curl)
// The login 'form' is at login.php
$ch = curl_init('http://domain.local/login.php');
// We are posting 2 variables, and returning the transfer just so it doesn't dump out
// Headers are processed by the callback function processHeaders()
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'processHeaders');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username=user&password=pass');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute curl, close the connection, and redirect the user to a 'restricted' page
$response = curl_exec($ch);
curl_close($ch);
header("Location: http://domain.local/restricted.php");
function processHeaders($ch, $header) {
// Dump the response headers to the client
header($header);
strlen($header);
}
login.php (Contains the 'login' form)
session_start();
if($_POST) {
if($_POST['username'] == 'user' && $_POST['password'] == 'pass') {
$_SESSION['auth'] = 1;
$_SESSION['token'] = md5(time());
} else {
echo 'Auth failed';
}
} else {
echo 'Invalid access type';
}
restricted.php (Restricted page)
session_start();
if($_SESSION['auth']) {
echo 'Secret Token: '.$_SESSION['token'];
} else {
echo 'Please log in';
}
The idea is that the user wants to ultimately get to 'restricted.php'. 'login.php' contains the code necessary to log in. What I want to simulate is the user filling out the form on 'login.php' and logging the user into 'restricted.php'.
The above snippets of code work together on my local tests (hitting autologin.php redirects to restricted.php and the secret token is printed out), but I can't seem to get it to work cross-application. The apps will be on the same domain (https://domain.com/myapp, https://domain.com:1234/vendorapp).
I've never done this before in any language, I'm just going off of what my vendor has told me they've done. Apparently they've never dealt with PHP before and have no idea what to do.
like this:
header("Location: http://www.example.com/")
But it must come before any other code...see php.net
You just output a normal HTTP redirect header() like this:
<?php header('Location: http://www.example.com/'); ?>
Re Update
If I understand correctly you'd need to do this:
Browser POSTs login request to PHP server
PHP script packages the login information in some specific form for JSP app
PHP script POSTs (via cURL) or SOAPs or whatever is necessary to JSP app
PHP receives the response and parses out the necessary information
PHP sends header and/or body data back to browser
Step 4, parsing the information, depends on how you send and receive the information. If you receive them in the header via cURL, you'll need to set CURLOPT_HEADER to true and parse the necessary data out of the response. This may be as simple as splitting the string on the first blank line or more complicated, that depends on your specific situation.
How this logs in the user in your app is something you need to handle as well. The JSP app probably handles the actual password and username and hands you back a token of some sort which you'll need to keep track of.
It sounds like you are looking for the curl library, which is usually bundled with PHP.
http://php.net/manual/en/book.curl.php
<?php
session_start();
// Receive username / password from $_POST
// Prepare CURL object for post
// Post u/p to java server
// Read response
if($success)
{
header('Location: nextpage.php');
$_SESSION['LoggedInTime'] = time();
exit;
}
else
{
//display error
}
Update:
Later, you can check $_SESSION['LoggedInTime'] + 3600 > time() to see if they are still logged in. Every time they visit a logged in page, do this:
if($_SESSION['LoggedInTime'] + 3600 > time())
{
$_SESSION['LoggedInTime'] = time() + 3600;
}
else
{
header('Location: /login.php?Message=session+expired');
exit;
}
Hope this helps.
If you are trying to integrate php and java on the web, you may want to look into Quercus/Resin. Your PHP can then call java code directly. Since they are running on the same server, the java code could write any cookies, setup any sessions or doing any necessary setup processing.
http://www.caucho.com/resin-3.0/quercus/tutorial/module/index.xtp