gpt4 book ai didi

java - 如何使用 x-www-form-urlencoded 正文发送发布请求

转载 作者:IT老高 更新时间:2023-10-28 20:51:30 25 4
gpt4 key购买 nike

Request in postman

如何在 java 中发送带有 x-www-form-urlencoded header 的请求。我不明白如何发送带有键值的正文,如上面的屏幕截图所示。

我试过这段代码:

String urlParameters =
cafedra_name+ data_to_send;
URL url;
HttpURLConnection connection = null;
try {
//Create connection
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");

connection.setRequestProperty("Content-Length", "" +
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");

connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);

//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();

但在响应中,我没有收到正确的数据。

最佳答案

由于您将 application/x-www-form-urlencoded 设置为内容类型,因此发送的数据必须是这种格式。

String urlParameters  = "param1=data1&param2=data2&param3=data3";

现在发送部分非常简单。

byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
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("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write( postData );
}

或者您可以创建一个通用方法来构建 application/x-www-form-urlencoded 所需的键值模式。

private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}

关于java - 如何使用 x-www-form-urlencoded 正文发送发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40574892/

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