Jakub Cermoch
Jakub Cermoch

Reputation: 41

cURL equivalent in Java

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

Upvotes: 4

Views: 14574

Answers (6)

Powerlord
Powerlord

Reputation: 88796

The cURL site links to Java Bindings on Github.

Upvotes: 2

Amit
Amit

Reputation: 34735

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();

Upvotes: 1

Quotidian
Quotidian

Reputation: 2940

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

Upvotes: 14

ChadNC
ChadNC

Reputation: 2503

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.

Upvotes: 2

dfa
dfa

Reputation: 116334

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.

Upvotes: 2

Yacoby
Yacoby

Reputation: 55445

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

Upvotes: 3

Related Questions