gpt4 book ai didi

java - 为什么 HTTP POST 返回代码 400(错误请求)? HTTP POST 方法

转载 作者:行者123 更新时间:2023-12-01 06:43:16 26 4
gpt4 key购买 nike

为什么服务器返回响应代码400(错误请求)? (不起作用)

URL serverAddress = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestMethod("POST");
int status = connection.getResponseCode(); // returns 400

例如,此 HTTP GET 返回代码 200:(有效)

/** Creating Connection **/
URL serverAddress = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestMethod("GET");
connection.setDoOutput(false);
int status = connection.getResponseCode(); // returns 200

最佳答案

在实际写入流并关闭流(writer.write())之前,我尝试获取响应代码(connection.getResponseCode())os.close() ) 这就是服务器返回错误请求代码 (400) 的原因。这是我现在可以使用的代码:

            /** Creating Connection **/
URL serverAddress = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestMethod("POST");

/** POSTing **/
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery());
writer.flush();
writer.close();
os.close();
connection.connect();

int status = connection.getResponseCode();//this cannot be invoked before data stream is ready when performing HTTP POST
PrinterClass.show(status); //status
if (status != 200)
throw (new RESTfulWebServiceException("Invalid HTTP response status "
+ "code " + status + " from web service server."));

private String getQuery() throws UnsupportedEncodingException
{
JSONObject jobj = new JSONObject();
jobj.put("customerNumber", new JSONString("003"));
jobj.put("mappingCode", new JSONString("jac_003"));
jobj.put("name", new JSONString("johnny"));
jobj.put("status", new JSONString("ACTIVE"));
PrinterClass.show(jobj.toString());
return jobj.toString();
}

关于java - 为什么 HTTP POST 返回代码 400(错误请求)? HTTP POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262364/

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