- 利用HttpURLConnection对象,我们可以向网络发送请求参数.
- String requestUrl = "http://localhost:8080/itcast/contanctmanage.do";
- Map<String, String> requestParams = new HashMap<String, String>();
- requestParams.put("age", "12");
- requestParams.put("name", "中国");
- StringBuilder params = new StringBuilder();
- for(Map.Entry<String, String> entry : requestParams.entrySet()){
- params.append(entry.getKey());
- params.append("=");
- params.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
- params.append("&");
- }
- if (params.length() > 0) params.deleteCharAt(params.length() - 1);
- byte[] data = params.toString().getBytes();
- URL realUrl = new URL(requestUrl);
- HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
- conn.setDoOutput(true);//发送POST请求必须设置允许输出
- conn.setUseCaches(false);//不使用Cache
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Connection", "Keep-Alive");//维持长连接
- conn.setRequestProperty("Charset", "UTF-8");
- conn.setRequestProperty("Content-Length", String.valueOf(data.length));
- conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
- DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
- outStream.write(data);
- outStream.flush();
- if( conn.getResponseCode() == 200 ){
- String result = readAsString(conn.getInputStream(), "UTF-8");
- outStream.close();
- System.out.println(result);
- }