4

i need to convert the following curl command into java command.

$curl_handle = curl_init ();

curl_setopt ($curl_handle, CURLOPT_URL,$url);`enter code here`
curl_setopt ($curl_handle, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt ($curl_handle, CURLOPT_POST, 1);
curl_setopt ($curl_handle, CURLOPT_POSTFIELDS, $postfields);

//echo $postfields;

$curl_result = curl_exec ($curl_handle) or die ("There has been a CURL_EXEC error");
2
  • 1
    Have you tried anything? Commented Jun 27, 2014 at 14:24
  • @TAsk basically it sends a xml string to link and get response from that Commented Jun 27, 2014 at 14:25

2 Answers 2

6

Http(s)UrlConnection may be your weapon of choice:

public String sendData() throws IOException {
    // curl_init and url
    URL url = new URL("http://some.host.com/somewhere/to/");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();

    //  CURLOPT_POST
    con.setRequestMethod("POST");

    // CURLOPT_FOLLOWLOCATION
    con.setInstanceFollowRedirects(true);

    String postData = "my_data_for_posting";
    con.setRequestProperty("Content-length", String.valueOf(postData.length()));

    con.setDoOutput(true);
    con.setDoInput(true);

    DataOutputStream output = new DataOutputStream(con.getOutputStream());
    output.writeBytes(postData);
    output.close();

    // "Post data send ... waiting for reply");
    int code = con.getResponseCode(); // 200 = HTTP_OK
    System.out.println("Response    (Code):" + code);
    System.out.println("Response (Message):" + con.getResponseMessage());

    // read the response
    DataInputStream input = new DataInputStream(con.getInputStream());
    int c;
    StringBuilder resultBuf = new StringBuilder();
    while ( (c = input.read()) != -1) {
        resultBuf.append((char) c);
    }
    input.close();

    return resultBuf.toString();
}

I'm not quite sure about the HTTPS_VERIFYPEER-thing, but this may give you a starting point.

Sign up to request clarification or add additional context in comments.

1 Comment

Casting a byte to a char is a bad idea.
1

Have a look at the java.net.URL and java.net.URLConnection libraries.

URL url = new URL("yourUrl.com");

Then use a an InputStreamReader & BufferedReader.

More information in Oracles example: http://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html

This might also help: How to use cURL in Java?

1 Comment

i am getting SSLHandShakeException while in php i disbaled CURL_VERIFYPEER = 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.