我正在尝试使用仅支持通过form-data或www-form-urlencoded属性传递JSON数据的REST API.因此,我的问题是,如何使用HttpUrlConnection附加多个表单数据项?当我通过浏览器使用API时,Chrome中的请求如下所示:
Form Data
adds:
updates: [{“attributes”:{“OBJECTID”:2241,”OTHER_FIELD”:”500″}}]
deletes:
gdbVersion:
rollbackOnFailure:
f: pjson
但是我不知道如何在Java中复制它.
到目前为止,这是我尝试过的:
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);
但是它没有像应该那样附加数据…
对于那些有兴趣的人,我尝试连接到ArcGIS要素服务API,以便可以添加,更新或删除要素,但是在这里,我正在使用ApplyEdits
解决方法:
所以我想出了解决方法,这是解决方案:
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
首先将请求设置为POST请求,然后会有一些输出
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"));
这就是设置每个表单数据值的方式.每个键值只是一个Java字符串,然后使用URLEncoder.encode对值进行编码.然后使用具有所有表单数据元素的字符串,将其写入输出流:
final BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream()));
bfw.write(encodedUrl);
bfw.flush();
bfw.close();
然后,可以接收并解析响应.
标签:arcgis,post,httpurlconnection,java
来源: https://codeday.me/bug/20191026/1937046.html