POST和GET區別

* 每一個HTTP-GET和HTTP-POST都由一系列HTTP請求頭組成,這些請求頭定義了客戶端從服務器請求了什麼,而響應則是由一系列HTTP請求數據和響應數據組成,若是請求成功則返回響應的數據。html

* HTTP-GET以使用MIME類型application/x-www-form-urlencoded的urlencoded文本的格式傳遞參數。Urlencoding是一種字符編碼,保證被傳送的參數由遵循規範的文本組成,例如一個空格的編碼是"%20"。附加參數還能被認爲是一個查詢字符串。安全

* 與HTTP-GET相似,HTTP-POST參數也是被URL編碼的。然而,變量名/變量值不做爲URL的一部分被傳送,而是放在實際的HTTP請求消息內部被傳送。服務器

* GET和POST之間的主要區別網絡

  一、GET是從服務器上獲取數據,POST是向服務器傳送數據。app

  二、在客戶端, GET方式在經過URL提交數據,數據在URL中能夠看到;POST方式,數據放置在HTML HEADER內提交post

  三、對於GET方式,服務器端用Request.QueryString獲取變量的值,對於POST方式,服務器端用Request.Form獲取提交的數據。this

  四、GET方式提交的數據最多隻能有1024字節,而POST則沒有此限制編碼

  五、安全性問題。正如在(2)中提到,使用 GET 的時候,參數會顯示在地址欄上,而 POST 不會。因此,若是這些數據是中文數據並且是非敏感數據,那麼使用 GET ;若是用戶輸入的數據不是中文字符並且包含敏感數據,那麼仍是使用 POST爲好url

* URL的定義和組成spa

  Uniform Resource Locator 統一資源定位符

  URL的組成部分:http://www.mbalib.com/china/index.htm

  http://:表明超文本傳輸協議

  www:表明一個萬維網服務器

  mbalib.com/:服務器的域名,或服務器名稱

  China/:子目錄,相似於咱們的文件夾

  Index.htm:是文件夾中的一個文件

  /china/index.htm統稱爲URL路徑

服務器端

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"); PrintWriter out = response.getWriter(); String username = request.getParameter("username"); System.out.println("-username->>"+username); String pswd = request.getParameter("password"); System.out.println("-password->>"+pswd); if(username.equals("admin")&&pswd.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
 } }

HTTP-GET方式

public class HttpUtils { private static String URL_PATH = "http://192.168.0.102:8080/myhttp/pro1.png"; public HttpUtils() { // TODO Auto-generated constructor stub
 } public static void saveImageToDisk() { InputStream inputStream = getInputStream(); byte[] data = new byte[1024]; int len = 0; FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream("C:\\test.png"); while ((len = inputStream.read(data)) != -1) { fileOutputStream.write(data, 0, len); } } catch (IOException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } } } } /** * 得到服務器端的數據,以InputStream形式返回 * @return
     */
    public static InputStream getInputStream() { InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try { URL url = new URL(URL_PATH); if (url != null) { httpURLConnection = (HttpURLConnection) url.openConnection(); // 設置鏈接網絡的超時時間
                httpURLConnection.setConnectTimeout(3000); httpURLConnection.setDoInput(true); // 表示設置本次http請求使用GET方式請求
                httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { // 從服務器得到一個輸入流
                    inputStream = httpURLConnection.getInputStream(); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } return inputStream; } public static void main(String[] args) { // 從服務器得到圖片保存到本地
 saveImageToDisk(); } }

HTTP-POST(Java接口)方式

public class HttpUtils { // 請求服務器端的url
    private static String PATH = "http://192.168.0.102: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(); } } /** * @param params * 填寫的url的參數 * @param encode * 字節編碼 * @return
     */
    public static String sendPostMessage(Map<String, String> params, String encode) { // 做爲StringBuffer初始化的字符串
        StringBuffer buffer = new StringBuffer(); try { if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { // 完成轉碼操做
                        buffer.append(entry.getKey()).append("=").append( URLEncoder.encode(entry.getValue(), encode)) .append("&"); } buffer.deleteCharAt(buffer.length() - 1); } // System.out.println(buffer.toString()); // 刪除掉最有一個&
 System.out.println("-->>"+buffer.toString()); HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); urlConnection.setConnectTimeout(3000); urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true);// 表示從服務器獲取數據
            urlConnection.setDoOutput(true);// 表示向服務器寫數據 // 得到上傳信息的字節大小以及長度
            byte[] mydata = buffer.toString().getBytes(); // 表示設置請求體的類型是文本類型
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setRequestProperty("Content-Length", String.valueOf(mydata.length)); // 得到輸出流,向服務器輸出數據
            OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(mydata,0,mydata.length); outputStream.close(); // 得到服務器響應的結果和狀態碼
            int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { return changeInputStream(urlConnection.getInputStream(), encode); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } return ""; } /** * 將一個輸入流轉換成指定編碼的字符串 * * @param inputStream * @param encode * @return
     */
    private static String changeInputStream(InputStream inputStream, String encode) { // TODO Auto-generated method stub
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; String result = ""; if (inputStream != null) { try { while ((len = inputStream.read(data)) != -1) { outputStream.write(data, 0, len); } result = new String(outputStream.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", "1234"); String result = HttpUtils.sendPostMessage(params, "utf-8"); System.out.println("--result->>" + result); } }

HTTP-POST(Apache接口)方式

public class HttpUtils { public HttpUtils() { // TODO Auto-generated constructor stub
 } public static String sendHttpClientPost(String path, Map<String, String> map, String encode) { List<NameValuePair> list = new ArrayList<NameValuePair>(); if (map != null && !map.isEmpty()) { for (Map.Entry<String, String> entry : map.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry .getValue())); } } try { // 實現將請求的參數封裝到表單中,請求體重
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode); // 使用Post方式提交數據
            HttpPost httpPost = new HttpPost(path); httpPost.setEntity(entity); // 指定post請求
            DefaultHttpClient client = new DefaultHttpClient(); HttpResponse httpResponse = client.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { return changeInputStream(httpResponse.getEntity().getContent(), encode); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block
 e.printStackTrace(); } return ""; } /** * 將一個輸入流轉換成指定編碼的字符串 * * @param inputStream * @param encode * @return
     */
    public static String changeInputStream(InputStream inputStream, String encode) { // TODO Auto-generated method stub
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; String result = ""; if (inputStream != null) { try { while ((len = inputStream.read(data)) != -1) { outputStream.write(data, 0, len); } result = new String(outputStream.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
        String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction"; Map<String, String> params = new HashMap<String, String>(); params.put("username", "admin"); params.put("password", "123"); String result = HttpUtils.sendHttpClientPost(path, params, "utf-8"); System.out.println("-->>"+result); } }
相關文章
相關標籤/搜索