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.
Related
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'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.
$ch = curl_init();
curl_setopt($ch, CURLOPT_FILE, $file);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, $urls[$vidCount]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_exec($ch);
curl_close($ch);
So I have a cURL request that takes a URL and produces a file in the filesystem.
How do I emulate the above PHP cURL request in Java?
I have tried HttpURLConnection, but I am getting 403 Forbidden. The same call in cURL works properly. Is there some architecture difference between the two that I need to reconcile?
I believe it could be something in the headers that cURL might be setting automatically where Java is not. I'm not really sure but I would appreciate any advice I can get.
Thanks.
I am not sure why you trying to emulate PHP behavior in Java. If the end result is really what you need to reach, than use the Java HttpURLConnection or even URLConnection.
is there any method that I can retrieve data (eg, username and password) from PHP to a Java servlet? Thanks
Create a POST request in PHP:
Use cURL:
$ch = curl_init('http://www.example.com:8080/my-servlet/');
$data = '...' # the data you want to send
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
A better, more concise approach, using pecl_http:
$response = http_post_data('http://www.example.com:8080/my-servlet/', $data);
POST and GET pretty much do not depend on the language being used, so if I understand your question correctly, you can use either $_POST['var'] in PHP or request.getParameter("var") in Java on the page that receives the POST data.
These are the steps:
POST Form (file/image input) from the browser goes to a PHP server.
The PHP server then use fsockopen to a Java (GlassFish/Jersey) REST service, sending the image as content for more advanced imaging work to be done there, and returning the resulting image back to the PHP server (or returning only a URI to the image).
The PHP server then echos the result (img src= ..) back to the user in the HTML document.
Getting the image and all its attributes in the first step works great, but I need help setting up the headers correctly in the POST request from PHP to the web service.
Current code:
$fp = fsockopen("domain..", 80, $errno, $errstr, 30);
$contentlength = $_FILES["photo_file"]["size"];
$imageref = $_FILES["photo_file"]["tmp_name"];
$out = "POST /Uri to resource .. HTTP/1.1\r\n";
$out .= "Host: http://... \r\n";
$out .= "Connection: Keep-Alive\r\n";
$out .= "Content-type: multipart/mixed\r\n";
$out .= "Content-length: $contentlength\r\n\r\n";
$out .= "$imageref";
fwrite($fp, $out);
$theOutput;
while (!feof($fp))
{
$theOutput .= fgets($fp, 128);
}
echo $theOutput;
fclose($fp);
Which echoes to the browser: "HTTP/1.1 400 Bad Request Content-Type: text/html Content-Length: 717".
So I need better formed headers to get through to the REST web-method. And if I should achieve that does anyone know what paramaters to use in the jersey web-method to access the image?
For standard HTML forms its this:
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response getFullImage(#FormDataParam("photo_file") InputStream imageIS {..ImageIO.read(imageIS)..}
Would love suggestions to better architecture also for achieving this in HTML.
Cheers
You probably have problem with badly written request and should use cURL at first place (in php), basic example usage (with writing to the file) from manual page:
$ch = curl_init("http://www.example.com/");
$fp = fopen("example_homepage.txt", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
Another example for setting post data from curl_setopt() page:
$data = array('name' => 'Foo', 'file' => '#/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
And handling HTTP status codes via curl_getinfo():
if(curl_getinfo($c, CURLINFO_HTTP_CODE) === 200){
...
}
You also may set http headers manually:
curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
"Content-Type: text/xml; charset=utf-8",
"Expect: 100-continue"
));