使用POST时HTTPUrlConnection给出400错误

时间:2018-11-02 08:30:26

标签: httpclient

尝试使用HTTPURLCOnnection进行发布操作,但无法获得正确的响应。 邮递员也一样。 下面的代码:

        URL url = new URL("<url>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Cookie", "value");

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");

        // send JSON Message to dataiku server
        String body = "{ 'login':'" + "<id>" + "','password':'" + "<pswd>"
                + "'" + "}";
        log.info("Payload: " + body);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
        outputStreamWriter.write(body);
        outputStreamWriter.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

错误:

java.io.IOException:服务器为URL返回HTTP响应代码:400     在sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1894)     在sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1492)     在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处     在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)     在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:498)     在com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:65)

任何人都可以帮助解决上面的代码出什么问题吗?

0 个答案:

没有答案