doPost方法源码如下(reqUrl为post的目标,parameters为要post的表单,recvEncoding为编码,ht为header、包括cookie的内容)
调用以后,用抓包软件发现post到服务器的包分成两个,一个只带header的内容,一个是我发送的数据
public String doPost(String reqUrl, Map parameters, String recvEncoding,Hashtable ht) {
HttpURLConnection url_con = null;
String responseContent = null;
try {
StringBuffer params = new StringBuffer();
for (Iterator iter = parameters.entrySet().iterator(); iter
.hasNext();) {
Entry element = (Entry) iter.next();
params.append(element.getKey().toString());
params.append("=");
params.append(URLEncoder.encode(element.getValue().toString(),
recvEncoding));
System.out.println(URLEncoder.encode(element.getValue().toString(),
recvEncoding));
params.append("&");
}
if (params.length() > 0) {
params = params.deleteCharAt(params.length() - 1);
}
System.out.println(params);
byte[] b = params.toString().getBytes();
URL url = new URL(reqUrl);
url_con = (HttpURLConnection) url.openConnection();
url_con.setRequestMethod("POST");
url_con.setConnectTimeout(5000);
url_con.setReadTimeout(5000);
//设置header
if (ht!=null){
Enumeration enu = ht.keys();
while (enu.hasMoreElements()){
try{
String f = (String)enu.nextElement();
String v = (String)ht.get(f);
System.out.println(String.valueOf(f)+"="+String.valueOf(v));
if (v!=null)
url_con.setRequestProperty(f,v);
}catch(Exception e){}
}
ht.put("Content-Length", String.valueOf(b.length));
}
url_con.setDoOutput(true);
OutputStream httpOutputStream = url_con.getOutputStream();
httpOutputStream.write(b);
httpOutputStream.flush();
httpOutputStream.close();
InputStream in = url_con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in,
recvEncoding));
String tempLine = rd.readLine();
StringBuffer tempStr = new StringBuffer();
String crlf = System.getProperty("line.separator");
while (tempLine != null) {
tempStr.append(tempLine);
tempStr.append(crlf);
tempLine = rd.readLine();
}
responseContent = tempStr.toString();
rd.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}catch(Exception e){
e.printStackTrace();
return "";
} finally {
if (url_con != null) {
url_con.disconnect();
}
}
return responseContent;
}
抓包结果如下: