【问题标题】:Java Put-Request returns 400 Bad RequestJava Put-Request 返回 400 错误请求
【发布时间】: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


【解决方案1】:

我在 cmd 提示符下执行了ipconfig,它显示了192.168.1.3。我在 Android 应用程序中将其更改为 localhost,现在我可以访问本地 Web 服务器了。

【讨论】:

    猜你喜欢
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-14
    • 2019-07-11
    相关资源
    最近更新 更多