Code:
- 利用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);
- }
216;mso-char-wrap:1;mso-kinsoku-overflow:1'>111%;visibility:hidden">left:43.5%;text-align:left;font-family:Wingdings;font-size:70%">l