如何使用x-www-form-urlencoded正文发送帖子请求 [英] How to send post request with x-www-form-urlencoded body
问题描述
如何在java中,我可以使用 x-www-form-urlencoded header
发送请求。我不明白如何发送一个带键值的正文,如上面的截图所示。
How in java, can I send a request with x-www-form-urlencoded header
. I don't understand how to send a body with a key-value, like in the above screenshot.
我试过这段代码:
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 ();
但在回复中,我没有收到正确的数据。
But in the response, I don't receive the correct data.
推荐答案
当您将 application / x-www-form-urlencoded
设置为内容类型时,所以必须发送数据就像这种格式。
As you set application/x-www-form-urlencoded
as content type so data sent must be like this format.
String urlParameters = "param1=data1¶m2=data2¶m3=data3";
现在发送部分非常简单。
Sending part now is quite straightforward.
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
。
Or you can create a generic method to build key value pattern which is required for 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();
}
这篇关于如何使用x-www-form-urlencoded正文发送帖子请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!