【发布时间】:2015-07-05 21:03:49
【问题描述】:
我尝试针对我编写的 rest-api 执行 put-request,但它总是返回 400-Bad Request。
java.io.IOException:服务器返回 HTTP 响应代码:400 用于 URL:http://localhost:8000/api/v0/contacts/2 在 sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
我可以使用 firefox-rest client-plugin 以及另一个 angular 客户端调用 url,所以我想我在 java 代码中配置了错误。
服务器总是返回一些东西,所以我不知道为什么当我尝试获取输入流时它会崩溃。
protected String put(String path, String parameters)
throws IOException {
HttpURLConnection connection = getConnection(path, "PUT", parameters);
OutputStreamWriter outputWriter = new OutputStreamWriter(
connection.getOutputStream());
outputWriter.write(parameters);
outputWriter.flush();
outputWriter.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String response = reader.readLine();
while(response != null){
response += reader.readLine();
}
reader.close();
return response;
}
private HttpURLConnection getConnection(String path, String method,String params) throws MalformedURLException, IOException,
ProtocolException {
URL url = new URL(this.api + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Length",
String.valueOf(params.length()));
return connection;
}
抱歉英语不好,这不是我的母语。
【问题讨论】:
-
如果我们不知道服务器运行什么样的应用程序(Tomcat、Spring Boot、Dropwizard)并查看您的后端代码,我们将无能为力。 400 可能是由于您的客户端缺少 Content-Type,但这只是猜测。
标签: java httpclient put http-status-code-400