尝试执行Post请求时出错400

时间:2016-05-09 20:28:31

标签: java http http-post

我试图用Java发布帖子请求,但是它返回了400错误。

代码:

        String urlParameters  = "UserName=xxxx&ApplicationId=xx";
        byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
        int    postDataLength = postData.length;
        String request        = "http://url/";
        URL    url            = new URL( request );
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
        conn.setDoOutput( true );
        conn.setInstanceFollowRedirects( false );
        conn.setRequestMethod( "POST" );
        conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
        conn.setRequestProperty( "User-Agent", "runscope/0.1");
        conn.setRequestProperty( "charset", "utf-8");
        conn.setRequestProperty( "Accept", "*/*");
        System.out.println(Integer.toString( postDataLength ));
        conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
        conn.setUseCaches( false );
        try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) {
           wr.write( postData );
        }

        System.out.println(conn.getContent().toString());

堆栈跟踪:

java.io.IOException: Server returned HTTP response code: 400 for URL: url
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at rest.Aplicacao.main(Aplicacao.java:42)

0 个答案:

没有答案