I'm trying to convert the following CURL request to Java
curl -H "public-api-token: 29sds38sd38xc339332dssdsdk22" -X PUT -d "testParameter=param1" https://server.com/url
(I've edited the server name and paramter name for other reasons but rest assured they're working perfectly fine when the above command is executed from terminal)
I've arrived at the following but now I'm stuck as I couldn't find what could cause the error:
import java.net.*;
import java.io.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.print(getResponseFromHttpUrl());
}
public static String getResponseFromHttpUrl() throws IOException {
URL url = new URL("https://server.com/url");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("PUT");
urlConnection.addRequestProperty("Accept", "application/json");
urlConnection.addRequestProperty("Content-Type", "application/json");
urlConnection.addRequestProperty("public-api-token", "29sds38sd38xc339332dssdsdk22");
String strFileContents = "";
try {
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(out, "UTF-8"));
writer.write("testParameter=param1");
writer.flush();
writer.close();
out.close();
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
byte[] contents = new byte[1024];
int bytesRead = 0;
while ((bytesRead = in .read(contents)) != -1) {
strFileContents += new String(contents, 0, bytesRead);
}
} catch( Exception e ) {
// if a more general exception was thrown, handle it here
System.out.println(e.getMessage());
} finally {
urlConnection.disconnect();
}
return strFileContents;
}
}
I suspect the method by which I supply the data might be wrong but not sure about it. Any suggestions?
PS: The error shown is
HelloWorld.java:8: error: unreported exception IOException; must be caught or declared to be thrown System.out.print(getResponseFromHttpUrl());