我想發送http post請求到某個服務器,並且參數包含空格以及一些特殊字符。以下是我的代碼:HttpURLConnection發送+而不是空間
public static String HttpPost(String[] paramName, String[] paramVal)
{
try{
String parameters = null;
if ((paramName != null) && (paramVal != null))
{
parameters = paramName[0] +"="+ paramVal[0];
for (int i = 1; i < paramName.length; i++)
{
parameters+= "&";
parameters += URLEncoder.encode(paramName[i], "US-ASCII") + "=" + URLEncoder.encode(paramVal[i], "utf-8");
}
}
//parameters = URLEncoder.encode(parameters, "utf-8");
byte[] postData = parameters.getBytes(StandardCharsets.US_ASCII);
int postDataLength = postData.length;
FolderManager fm = new FolderManager();
String urlStr = FolderManager.ApplicationUnderTestUrl();
URL url = new URL(urlStr);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
//con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
conn.setRequestProperty("Accept", "application/x-www-form-urlencoded; charset=US-ASCII");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=US-ASCII");
conn.setRequestProperty("charset", "US-ASCII");
conn.setRequestProperty("Accept-Encoding", "identity");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.write(postData);
//System.out.print(postData);
}
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
System.out.println(line);
return line;
}
reader.close();
return line;
}catch(Exception e)
{
return e.getMessage();
}
}
上面的代碼發送特殊字符,但它會發送'+'符號,以便在params中有一個空格。我如何避免這種情況?
這就是它應該做的。你爲什麼認爲你需要避免它?並請修正您的標題。它與你的問題相矛盾。 – EJP
請參閱https://en.wikipedia.org/wiki/Percent-encoding#The_application.2Fx-www-form-urlencoded_type關於爲什麼您正在觀察的行爲是正確的 –
我正在發送一些文件和文件夾的名稱以及一些用戶界面元素放到服務器端,並且它們中有空格。如果發送'+'而不是空格,我的服務器將失敗。所以我需要一些方法來避免替換 – CodingIsComplex