【发布时间】:2018-04-26 05:54:03
【问题描述】:
如何使用带有查询参数的HttpURLConnection 发出 PUT 请求?
我正在尝试使用 HttpURLConnection 使用第三方 REST API,但是当我尝试在 URL 中传递参数时,它不起作用并抛出如下所示的错误:
在映射注册表中找不到 REST API 网址
这是目前对我不起作用的代码块:
URL url;
StringBuffer response = new StringBuffer();
try
{
url = new URL(" http://thirdparty.com/party/api/v2/ksp/12/ks");
HttpURLConnection httpURL = (HttpURLConnection) url.openConnection();
httpURL.setDoOutput(true);
httpURL.setRequestMethod("PUT");
StringBuilder sbUrl = new StringBuilder("parameter1_id=");
sbUrl.append(getParameter1Value())
.append("¶meter2_id=")
.append(getParameter2Value());
final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURL.getOutputStream()));
writer.write(sbUrl.toString());
writer.flush();
writer.close();
// throw the exception here in case invocation of web service
if (httpURL.getResponseCode() != 200)
{
// throw exception
}
else
{
//SUCCESS
}
}
catch (IOException e)
{
}
当我在正文中将这些参数作为form-data 参数提供时,REST API 似乎提供了响应。
我的问题是如何使用 HttpURLConnection 进行这项工作?
到目前为止我尝试了什么? 我已经尝试将上面的内容修改为类似下面的内容,但它不起作用。
try
{
url = new URL(" http://thirdparty.com/party/api/v2/ksp/12/ks");
HttpURLConnection httpURL = (HttpURLConnection) url.openConnection();
httpURL.setDoOutput(true);
httpURL.setRequestMethod("PUT");
httpURL.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + "----WebKitFormBoundarydklhfklsdfhlksh");
dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"parameter1_id\"");
dataOutputStream.writeBytes("\r\n" + "parameter1Value" +"\r\n");
dataOutputStream.writeBytes("--" + "----WebKitFormBoundarydklhfklsdfhlksh");
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"parameter2_id\"");
dataOutputStream.writeBytes("\r\n" + "parameter2Value" + "\r\n");
dataOutputStream.writeBytes("--" + "----WebKitFormBoundarydklhfklsdfhlksh" + "--");
dataOutputStream.flush();
dataOutputStream.close();
urlConnection.connect();
// throw the exception here in case invocation of web service
if (httpURL.getResponseCode() != 200)
{
// throw exception
}
else
{
//SUCCESS
}
}
catch (IOException e)
{
}
EDIT:它会抛出一个错误,响应代码为 500
编辑:澄清一下,我不是在尝试上传文件,而是尝试在 BODY 中发送参数(例如查询参数,而不是作为 URL 参数发送)。
非常感谢您对此的任何指示或建议。
【问题讨论】:
-
从不捕获异常而不处理它,至少记录它们
-
是的,我已经在我的代码中实现了,但是为了给出实际代码块的图片,添加了这个空的
catch块 -
获取“在映射注册表中找不到 REST API Url”的任何其他人的信息:当您对端点使用错误动词时(例如一个只需要 GET 的端点的 POST)
标签: java rest httpurlconnection