gpt4 book ai didi

java - HttpUrlConnection POST 给出 400 Bad Request。所有输入字段均正确

转载 作者:太空宇宙 更新时间:2023-11-04 10:39:02 27 4
gpt4 key购买 nike

我正在尝试 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());

最佳答案

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);

应该可以完成这项工作。

关于java - HttpUrlConnection POST 给出 400 Bad Request。所有输入字段均正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215949/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com