servlet-使用dopost方式提交資料(程式碼範例)

來源:互聯網
上載者:User

代碼來自:http://blog.csdn.net/neu_yousei/article/details/22486983

用戶端代碼

package com.http.post;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import java.util.HashMap;import java.util.Map;public class HttpUtils {// 表示伺服器端的urlprivate static String PATH = "http://192.168.0.100:8080/myhttp/servlet/LoginAction";private static URL url;public HttpUtils() {// TODO Auto-generated constructor stub}static {try {url = new URL(PATH);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/* * params 填寫的URL的參數 encode 位元組編碼 */public static String sendPostMessage(Map<String, String> params,String encode) {StringBuffer stringBuffer = new StringBuffer();if (params != null && !params.isEmpty()) {for (Map.Entry<String, String> entry : params.entrySet()) {try {stringBuffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 刪掉最後一個 & 字元stringBuffer.deleteCharAt(stringBuffer.length() - 1);System.out.println("-->>" + stringBuffer.toString());try {HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setConnectTimeout(3000);httpURLConnection.setDoInput(true);// 從伺服器擷取資料httpURLConnection.setDoOutput(true);// 向伺服器寫入資料// 獲得上傳資訊的位元組大小及長度byte[] mydata = stringBuffer.toString().getBytes();// 佈建要求體的類型httpURLConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");httpURLConnection.setRequestProperty("Content-Lenth",String.valueOf(mydata.length));// 獲得輸出資料流,向伺服器輸出資料OutputStream outputStream = (OutputStream) httpURLConnection.getOutputStream();outputStream.write(mydata);// 獲得伺服器響應的結果和狀態代碼int responseCode = httpURLConnection.getResponseCode();if (responseCode == 200) {// 獲得輸入資料流,從伺服器端獲得資料InputStream inputStream = (InputStream) httpURLConnection.getInputStream();return (changeInputStream(inputStream, encode));}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return "";}/* * // 把從輸入資料流InputStream按指定編碼格式encode變成字串String */public static String changeInputStream(InputStream inputStream,String encode) {// ByteArrayOutputStream 一般叫做記憶體流ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;String result = "";if (inputStream != null) {try {while ((len = inputStream.read(data)) != -1) {byteArrayOutputStream.write(data, 0, len);}result = new String(byteArrayOutputStream.toByteArray(), encode);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return result;}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubMap<String, String> params = new HashMap<String, String>();params.put("username", "admin");params.put("password", "123");String result = sendPostMessage(params, "utf-8");System.out.println("-result->>" + result);}}

伺服器端代碼

package com.login.manager;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginAction extends HttpServlet {/** * Constructor of the object. */public LoginAction() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> *  * This method is called when a form has its tag value method equals to get. *  * @param request *            the request send by the client to the server * @param response *            the response send by the server to the client * @throws ServletException *             if an error occurred * @throws IOException *             if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}/** * The doPost method of the servlet. <br> *  * This method is called when a form has its tag value method equals to * post. *  * @param request *            the request send by the client to the server * @param response *            the response send by the server to the client * @throws ServletException *             if an error occurred * @throws IOException *             if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");//用戶端 HttpUtils並沒有寫request方法是post ,但伺服器端可自動識別String method = request.getMethod();System.out.println("request method :"+method);PrintWriter out = response.getWriter();String username = request.getParameter("username");System.out.println("-username->>"+username);String password = request.getParameter("password");System.out.println("-password->>"+password);if (username.equals("admin") && password.equals("123")) {// 表示伺服器段返回的結果out.print("login is success !");} else {out.print("login is fail !");}out.flush();out.close();}/** * Initialization of the servlet. <br> *  * @throws ServletException *             if an error occurs */public void init() throws ServletException {// Put your code here}}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.