0

How do I do the equivalent of this:

curl \
  --insecure \
  --request POST \
  --header "<header>" \
  --data "<Complex JSON Object>" \
  "https://<username>:<password>@<URL>?<params>"

in Java?

The authentication is weird and only works if I use the --insecure flag and the basic authentication.

I've tried all sorts of libraries, but I can't get it to work.

  • `-k` / `--insecure` is documented as "Allow connections to SSL sites without certs (H)"; but your site isn't an SSL site, so that flag shouldn't have any effect. Are you sure that your command means what you intend? – ruakh Aug 07 '17 at 01:38
  • Yes. I know what it does. I forgot the "s" when I posted this. Thanks for pointing it out. – Zachary Laborde Aug 07 '17 at 02:15
  • OK. So, is your problem that you don't know how to achieve the equivalent of `--insecure`, or that you don't know how to achieve basic auth, or . . . ? – ruakh Aug 07 '17 at 03:45
  • @ruakh I don't know how to achieve the equivalent of `--insecure`. – Zachary Laborde Aug 07 '17 at 15:52
  • Process process = Runtime.getRuntime().exec(" curl -k -X POST --header \"Content-Type: application/json\" -d '"+body+"' https://u.r.l. "); process.waitFor(); process.destroy(); – loser8 Jan 09 '21 at 16:27

1 Answers1

-1

There are a ton http client libraries. One of the most popular is Apache Commons HTTP Client. You can use it to post JSON like this:

CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://www.example.com");

String json = "{"id":1,"name":"John"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

CloseableHttpResponse response = client.execute(httpPost);
assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
client.close();
Strelok
  • 50,229
  • 9
  • 102
  • 115
  • I need it to have the -k (--insecure) flag. It just returns: `Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target` – Zachary Laborde Aug 07 '17 at 01:43