我们都知道,Java的HttpURLConnection在使用post方式发送请求的时候,会使用一个输出流,将请求的具体数据以网络字节流的形式发送给目标主机。利用HttpURLConnection发送post请求的代码示意如下:
public String executePostByUsual(String actionURL, HashMap<String, String> parameters){
String response = "";
try{
URL url = new URL(actionURL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//发送post请求需要下面两行
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");;
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求数据内容
String requestContent = "";
Set<String> keys = parameters.keySet();
for(String key : keys){
requestContent = requestContent + key + "=" + parameters.get(key) + "&";
}
requestContent = requestContent.substring(0, requestContent.lastIndexOf("&"));
DataOutputStream ds = new DataOutputStream(connection.getOutputStream());
//使用write(requestContent.getBytes())是为了防止中文出现乱码
ds.write(requestContent.getBytes());
ds.flush();
try{
//获取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String s = "";
String temp = "";
while((temp = reader.readLine()) != null){
s += temp;
}
response = s;
reader.close();
}cat