1. 程式人生 > >Http使用post方式提交資料(使用java標準介面)

Http使用post方式提交資料(使用java標準介面)

本文內容:使用java標準介面,實現http用post方式提交資料。

-------------------------------------------------------------------------------------------------------------

程式組成部分:

1.客戶端用eclipse HttpUtils.java 標準java介面,實現http用post方式提交資料。 (用post方式提交 username 和 password)

2.伺服器端用myeclipse+tomcat 對客戶端請求進行相應。(若使用者名稱密碼正確,則返回字串"login is success !" ,不正確則返回字串“login is fail !”)

重點注意點:

1. public static String sendPostMessage(Map<String,String> params , String encode)

    目的: 在客戶端向伺服器端傳送 資料 params , 最終獲取從伺服器返回的輸入流,最終將該輸入流轉換成字串。注意使用標準java介面如何實現http的post請求,成功與伺服器連線,並且獲得從伺服器端響應返回的資料。

2. public String String changInputStream(InputStream inputStream , String encode)

    目的: 將一個輸入流按照指定編碼方式轉變成一個字串。(本例中是指,將從伺服器端返回的輸入流InputStream轉變成一個字串String,編碼方式是encode方式)

3. Map<String ,String> 的例項化方法及迭代方法

  Map  的例項化方法:

  Map<String, String> params = new HashMap<String, String>();
  params.put("username", "admin");
  params.put("password", "123");

   Map 的迭代方法:

 StringBuffer stringBuffer = new StringBuffer();

 
   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 block
     e.printStackTrace();
   
   }
   // 刪掉最後一個 & 字元
   stringBuffer.deleteCharAt(stringBuffer.length() - 1);

----------------------------------------------------------------------------------------------------------------

程式思路:

1. 客戶端建立http連結httpURLConnection,使用OutputStream向伺服器傳入資料

2. 獲得從伺服器端返回的輸入流InputStream

3. 將InputStream轉換成字串String

----------------------------------------------------------------------------------------------------------------

程式執行效果:

1.客戶端執行效果

2. 伺服器端執行結果

關鍵程式碼:

1. 客戶端 HttpUtils.java

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 {

	// 表示伺服器端的url
	private 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 block
			e.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 block
					e.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 block
				e.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 block
				e.printStackTrace();
			}

		}

		return result;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<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);

	}

}

伺服器端servlet: LoginAction.java

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
	}

}