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.
Related
I am working on an app that will help me log in the website and view data that I need. While I have no trouble with making sure that I parse that data and work with it properly, I did face an issue with logging into the website. I tried sending POST request, yet that didn't really work for some reason so I started looking more closely into how POST request to that website is sent in the browser and here is what I got:
Picture
I also asked a guy who developed that website and he said that I should use two cookies with "ulogin" and "upassword" for my log in. I tried using JSOUP as shown right here: https://jsoup.org/cookbook/input/load-document-from-url
I used .cookies("upassword", "10101010"), yet it didn't work so it makes me think that there is a bit more to it than just writing a simple line a post request.
Please, can someone explain to me how do I use cookies to log into website or at least point me in the direction where I can learn that, because I am so close to making that app happen and I will be able to proceed further with it's development, but it's just this one step that I am really being stuck with.
Here is an additional picture with Response and Request Headers from the Firefox. Picture
I managed to get it working a long time, yet didn't post an answer. So, here we go.
Cookies are just simple Headers, therefore you should treat them as such. In my case, with the use of HttpURLConnection, here is a piece of working code:
Note: My original request is for Java, however, I have since moved to Kotlin, so this solution uses Kotlin and this function is a "suspend" function which means that it is designed to be used with Kotlin Couroutines.
suspend fun httpRequest(): String {
val conn: HttpURLConnection = url_profile.openConnection() as HttpURLConnection
conn.requestMethod = "POST"
conn.doOutput = true
conn.doInput = true
conn.setRequestProperty(
"Cookie",
"YOUR COOKIE DATA"
)
val input: BufferedReader = BufferedReader(InputStreamReader(conn.inputStream))
return input.readText()
}
I'm start learning java programming, and I want make a simple server application. I read about com.sun.net.httpserver.HttpServer and find a good example on this link: https://github.com/imetaxas/score-board-httpserver-corejava.
I understand how to do Get-request in url, but I don't know how POST works. I think it must be sent a form or data on the server.
I attach the link of project, which I'm learning, in readme the author wrote http://localhost:8081/2/score?sessionkey=UICSNDK - it's not working...
I wrote in url and get sessionkey: "localhost:8081/4711/login --> UICSNDK"
I wrote in url this for Post request: "localhost:8081/2/score?sessionkey=UICSNDK" - not working and in chrome return 404 bad request
3.wrote in url this:"localhost:8081/2/highscorelist"
Please help me, I am beginner.
The difference between GET and POST is that with a GET request the data you wish to pass to the endpoint is done by modifying the url itself by adding parameters to it.
With a POST any data you wish to send to the endpoint must be in the body of the request.
The body of a request is arbitrary data that comes after a blank line in the header The reqiest has the request line, following by any number of header attributes, then a blank line.
The server would need to know what the format of the body of the request was and parse it as appropriate.
Of course 'modern' frameworks like jax-rs allow you to automatically convert request data to objects, so that it is much simpler.
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.
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