HttpUrlConnection POST提供400 Bad Request。所有输入字段都是正确的

时间:2018-03-11 02:07:51

标签: java rest post httpurlconnection

我正在尝试使用POST API,它可以使用cURL命令或POSTMan。但是,通过HttpURLConnection发送相同的调用并不起作用。 尝试过编码请求参数的URL。仍然没有运气。 HttpURLConnection的POST使用可能有问题。

    String url = "CORRECT_URL";
    URL obj = new URL(url);

    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    String urlParameters = "first_name=John&middle_name=Alfred&last_name=Smith&email=john.smith@gmail.com&phone=5555555555&zipcode=90401&dob=1970-01-22&ssn=543-43-4645&driver_license_number=F211165&driver_license_state=CA";
    byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
    int    postDataLength = postData.length;

    con.setRequestMethod("POST");
    con.setRequestProperty("Authorization", "Basic AUTH_TOKEN=");
    con.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
    con.setRequestProperty( "charset", "utf-8");
    con.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
    con.setUseCaches( false );

    try {
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.write(postData);
        wr.flush();
        wr.close();
  }
  catch(Exception e) {
    System.out.println("Server returned error!");
    con.getResponseMessage();
  }

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);
    System.out.println("Response : " + con.getResponseMessage());

1 个答案:

答案 0 :(得分:0)

byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
...
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(postData);

太过分了。

PrintWriter out = new PrintWriter(
   new OutputStreamWriter(con.getOutputStream(), "UTF-8")
);
out.print(urlParameters);

应该做的。