如何使用HttpURLConnection
发送带有查询参数的PUT请求?
我正在尝试使用HttpURLConnection
调用第三方REST API,但当我尝试在URL中传递参数时,它无法正常工作,并显示以下错误:
在映射注册表中找不到REST API Url
以下是目前对我无效的代码块:
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)
{
}
编辑:它会抛出一个响应代码为500的错误。
编辑:仅澄清一下,我不是在尝试上传文件,而是在尝试将参数发送到BODY中(就像查询参数一样,而不是作为URL参数发送)。
非常感谢您对此提供任何指针或建议。