tags:

views:

730

answers:

6

Hi,

I had

exec(
  "curl".
  " --cert $this->_cCertifikatZPKomunikace".
  " --cacert $this->_cCertifikatPortalCA".
  " --data \"request=".urlencode($fc_xml)."\"".
  " --output $lc_filename_stdout".
  " $this->_cPortalURL".
  " 2>$lc_filename_stderr",
  $la_dummy,$ln_RetCode
);

in php.

I have to do it via java. Can you help me?

Thanks Jakub

+2  A: 

Take a look at URLConnection. Sun has some examples. It has various subclasses that support some specific HTTP and HTTPS features.

Yacoby
+7  A: 

I use the HttpClient methods:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;

like so:

HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://www.google.com");
int responseCode = client.executeMethod(method);
if (responseCode != 200) {
    throw new HttpException("HttpMethod Returned Status Code: " + responseCode + " when attempting: " + url);
}
String rtn = StringEscapeUtils.unescapeHtml(method.getResponseBodyAsString());

EDIT: Oops. StringEscapeUtils comes from commons-lang. http://commons.apache.org/lang/api/org/apache/commons/lang/StringEscapeUtils.html

Quotidian
+1 HTTPClient is the way to go: http://hc.apache.org/httpcomponents-client/index.html
Malax
HTTPClient is great but the code you show would fail as it does not address certs...
harschware
+2  A: 

in addition to the pure Java answers by Quotidian and Yacoby you can try to execute the curl binary as in php. Check out how to use the ProcessBuilder class.

dfa
+1  A: 

You can execute commands in Java by using the Runtime with a call to getRuntime()

link to the javadoc for Runtime.

Here's a decent example of using Runtime.

Here's a decent example using Runtime or ProcessBuilder.

I hope some of that is helpful.

ChadNC
+1  A: 

The cURL site has Java Bindings.

R. Bemrose
Yeah but then it wouldn't be a pure java solution, which is (IMO) the major advantage of Java.
Kristopher Ives
(+1) yeah but it would make working with certs easy and it would translate from his original call rather nicely.
harschware
A: 

You can use HtmlUnit API in Java

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

like so:

WebClient webClient = new WebClient();
HtmlPage homePage = webClient.getPage("http://www.google.com");
String homePageString = homePage.asXml();
Yatendra Goel