I am attempting to use a REST API that only supports passing JSON data through the form-data or www-form-urlencoded attributes. So, my question is, how do I use an HttpUrlConnection to attach multiple form data items? When I use the API through the browser the request looks like this in Chrome:
Form Data
adds:
updates: [{"attributes":{"OBJECTID":2241,"OTHER_FIELD":"500"}}]
deletes:
gdbVersion:
rollbackOnFailure:
f: pjson
But I can't figure out how to replicate this in Java.
This is what I've tried so far:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.addRequestProperty("f", "json");
urlConnection.addRequestProperty("adds", null);
urlConnection.addRequestProperty("updates", "[{\"attributes\":{\"OBJECTID\":2241,\"OTHER_FIELD\":\"500\"}}]");
urlConnection.addRequestProperty("deletes", null);
urlConnection.addRequestProperty("rollbackOnFailure", "true");
urlConnection.addRequestProperty("gdbVersion", null);
But it doesn't attach the data as it should...
To those interested I am trying to connect to an ArcGIS feature service API so that I can add, update, or delete features but here I am using ApplyEdits
So I figured out how to solve this and here is the solution:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
First set the request to be a POST request and that there will be some output
StringBuilder encodedUrl = new StringBuilder("adds=" + URLEncoder.encode("[{\"attributes\":{\"OBJECTID\":2241,\"MAXIMOID_PRE\":\"HYD\"}}]", "UTF-8"));
encodedUrl.append("&updates=" + URLEncoder.encode("", "UTF-8"));
encodedUrl.append("&deletes=" + URLEncoder.encode("", "UTF-8"));
encodedUrl.append("&f=" + URLEncoder.encode("json", "UTF-8"));
encodedUrl.append("&rollbackOnFailure=" + URLEncoder.encode("true", "UTF-8"));
encodedUrl.append("&gdbVersion=" + URLEncoder.encode("", "UTF-8"));
This is how each of the form-data values gets set. Each key value is just a java string and then the value is encoded using the URLEncoder.encode. Using this string that has all of the form-data elements we then write it to the outputstream:
final BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
bfw.write(encodedUrl);
bfw.flush();
bfw.close();
Then after that the response can be received and parsed out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With