Java 当我试图向HTTP post请求发送参数以访问RESTful API时,我得到一个;“错误请求”;错误
我正在用Java编写代码。 API接受以下格式的输入:{input:[123345]“} 我的HTTP Post请求代码如下:Java 当我试图向HTTP post请求发送参数以访问RESTful API时,我得到一个;“错误请求”;错误,java,rest,Java,Rest,我正在用Java编写代码。 API接受以下格式的输入:{input:[123345]“} 我的HTTP Post请求代码如下: 输入参数:urlStr是我要连接到的API的URL paramVal的格式为JSONObject.toString 创建paramVal值的代码: int[] param_value = {123}; JSONObject obj=new JSONObject(); obj.put("job_ids", param_value); String response = h
输入参数:urlStr是我要连接到的API的URL paramVal的格式为JSONObject.toString 创建paramVal值的代码:
int[] param_value = {123};
JSONObject obj=new JSONObject();
obj.put("job_ids", param_value);
String response = httpPost(url,obj.toString)
在调试器中选中时,paramVal的inside httpPost值为
{“输入”:[123]}
我收到此HTTP post调用的错误请求错误。
我对RESTful API非常陌生,并且是第一次使用它。请帮助我查找代码中的错误我发现了两个潜在问题:(1)您说它接受
{input:[123345]“}
,这是一个包含一个值为字符串的元素的对象。但是您正在发送{“input”:[123]}
这是一个对象,其中一个元素的值是数组。(2) 您发送的JSON内容类型错误。@Real怀疑论者感谢您指出这一点。为了解决第一个潜在问题,我在代码中做了以下更改:int[]param_value={123};JSONObject obj=新的JSONObject();JSONArray jsArray=新的JSONArray(参数值);put(“job_id”,jsArray.toString());现在paramValue的值是{“input”:“[123]”格式。但是,我仍然收到错误的请求错误。您能解释一下如何修复JSON的内容类型吗?是否有一些用于Web服务的代码?日志中有异常吗?首先,不要在注释中放一堆代码。你可以编辑你的答案,写上“我改变了某某”,然后在评论中说“@someone,我编辑了这个问题,请做……”。内容类型应为application/json
@realponsignist谢谢!成功了。我会记住你关于评论的建议。
public static String httpPost(String urlStr, String paramVal) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
// Create the form content
if (paramVal != null){
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out);
writer.write(paramVal);
writer.close();
out.close();
}
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}