POST和GET区别

Posted 嘉禾世兴

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POST和GET区别相关的知识,希望对你有一定的参考价值。

* 每个HTTP-GET和HTTP-POST都由一系列HTTP请求头组成,这些请求头定义了客户端从服务器请求了什么,而响应则是由一系列HTTP请求数据和响应数据组成,如果请求成功则返回响应的数据。

* HTTP-GET以使用MIME类型application/x-www-form-urlencoded的urlencoded文本的格式传递参数。Urlencoding是一种字符编码,保证被传送的参数由遵循规范的文本组成,例如一个空格的编码是"%20"。附加参数还能被认为是一个查询字符串。

* 与HTTP-GET类似,HTTP-POST参数也是被URL编码的。然而,变量名/变量值不作为URL的一部分被传送,而是放在实际的HTTP请求消息内部被传送。

* GET和POST之间的主要区别

  1、GET是从服务器上获取数据,POST是向服务器传送数据。

  2、在客户端, GET方式在通过URL提交数据,数据在URL中可以看到;POST方式,数据放置在html HEADER内提交

  3、对于GET方式,服务器端用Request.QueryString获取变量的值,对于POST方式,服务器端用Request.Form获取提交的数据。

  4、GET方式提交的数据最多只能有1024字节,而POST则没有此限制

  5、安全性问题。正如在(2)中提到,使用 GET 的时候,参数会显示在地址栏上,而 POST 不会。所以,如果这些数据是中文数据而且是非敏感数据,那么使用 GET ;如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用 POST为好

* URL的定义和组成

  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);
    }

}

 

以上是关于POST和GET区别的主要内容,如果未能解决你的问题,请参考以下文章

axios post和get的区别

Python snippet(代码片段)

asp.net页面的提交方式POST和GET有啥区别?

$.ajax(),$.get(),$.post()的区别,以及一些参数注意规则

POST和GET的详细解释以及区别

get请求和post请求区别