我有一个发帖请求。在请求的正文中,有如下数据:
"username=michel&password=abc+defg"
当我发布发送请求时,我使用Packet Capture进行嗅探,当我查看数据时,看到的是“”(空格)而不是“ +”(加号),在我的情况下看起来像这样:
"username=michel&password=abc defg"
以UTF-8编码的数据。
这是我的代码(在添加之前以UTF-8编码的dataToSend)
public static HttpWebResponse getHttpWebResponse(String url, String cookie, StringBuffer dataToSend, String referer) {
HttpWebResponse response = new HttpWebResponse();
try {
http_connect = (HttpURLConnection) new URL(url).openConnection();//, Connector.READ_WRITE, true);
if (!isNullOrEmpty(dataToSend)) {
http_connect.setRequestMethod("POST");
http_connect.setDoInput(true);
http_connect.setDoOutput(true);
} else {
http_connect.setRequestMethod("GET");
}
http_connect.setInstanceFollowRedirects(false);
if (!isNullOrEmpty(cookie)) {
COOKIES.append(cookie);
}
http_connect.setRequestProperty("cookie", COOKIES.toString());
http_connect.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)");
http_connect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
http_connect.setRequestProperty("Http-version", "HTTP/1.1");
http_connect.setRequestProperty("Cache-Control", "no-cache");
http_connect.setRequestProperty("connection", "Keep-Alive");
if (!isNullOrEmpty(dataToSend))
http_connect.setRequestProperty("Content-Length", String.valueOf(dataToSend.toString().getBytes("UTF-8").length));//
if (!isNullOrEmpty(referer))
http_connect.setRequestProperty("Referer", referer);
http_connect.setConnectTimeout(App.DEFAULT_TIMEOUT);
if (!isNullOrEmpty(dataToSend)) {
http_os = http_connect.getOutputStream();
http_os.write(dataToSend.toString().getBytes("UTF-8"));
http_os.flush();
}
response.result = http_connect.getResponseCode();
response.location = http_connect.getHeaderField("location");
response.cookies = getAllCookiesFromHeader(http_connect);
if (response.result == HttpURLConnection.HTTP_OK) {
http_is = http_connect.getInputStream();
int ch = 0;
byte[] buff = new byte[512];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while (((ch = http_is.read(buff)) != -1)) {
if (ch < 512)
baos.write(buff, 0, ch);
else
baos.write(buff);
buff = new byte[512];
}
if (baos.size() > 0) {
response.body = new String(baos.toByteArray(), "UTF-8");
}
}
Logger.log("urlTest2 = " + url.toString() + ", response = " + http_connect.getResponseCode());
} catch (Exception e) {
} finally {
}
return response;
}