1

i have looked into different threads on stack overflow and done some research, i am unable to run this code in java after making a http connection. The same command works perfectly fine in the command line

curl -X POST --header "Content-Type: application/json" --header "Accept: */*" -d "data" "http://a url"

I need a java code for the above curl command, i have been unable to come up with anything worthy yet

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
flux
  • 81
  • 1
  • 1
  • 8
  • 1
    The thread does not concern itself with a java code for curl post method – flux Jun 24 '17 at 02:36
  • So, what threads have you found? What HTTP library are you using? – OneCricketeer Jun 24 '17 at 02:42
  • https://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection background.. get the WriteStream on the request and use a writer to put -d data from curl onto the Request.OutStream. set the headers ( just Content-type probably dont need Accept and .. should be good – Robert Rowntree Jun 24 '17 at 02:51
  • @cricket_007 https://stackoverflow.com/questions/9623158/curl-and-httpurlconnection-post-json-data – flux Jun 24 '17 at 02:58
  • @VasylLyashkevych is it? the thread you have mentioned has hardly anything to do with java implementation of curl commands – flux Jun 24 '17 at 03:02

1 Answers1

7

For anyone still looking

{String urly = "your url";
URL obj = new URL(urly);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestMethod("POST");
con.setRequestProperty("Content-Type","application/json");


con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(the data string);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);

BufferedReader iny = new BufferedReader(
new InputStreamReader(con.getInputStream()));
  String output;
  StringBuffer response = new StringBuffer();

  while ((output = iny.readLine()) != null) {
   response.append(output);
  }
  iny.close();

  //printing result from response
  System.out.println(response.toString());
 }
flux
  • 81
  • 1
  • 1
  • 8