在java如何添加表单_Java-如何通过HttpUrlConnection发送表单数据或www-form-urlencoded数据...

我正在尝试使用仅支持通过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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值