* 每个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 extendsHttpServlet {/*** Constructor of the object.*/

publicLoginAction() {super();

}/*** Destruction of the servlet.
*/

public voiddestroy() {super.destroy(); //Just puts "destroy" string in log//Put your code here

}/*** The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/

public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {this.doPost(request, response);

}/*** The doPost method of the servlet.

*

* This method is called when a form has its tag value method equals to post.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/

public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, 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.

*

*@throwsServletException if an error occurs*/

public void init() throwsServletException {//Put your code here

}

}

HTTP-GET方式

public classHttpUtils {private static String URL_PATH = "http://192.168.0.102:8080/myhttp/pro1.png";publicHttpUtils() {//TODO Auto-generated constructor stub

}public static voidsaveImageToDisk() {

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 staticInputStream getInputStream() {

InputStream inputStream= null;

HttpURLConnection httpURLConnection= null;try{

URL url= newURL(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();

}returninputStream;

}public static voidmain(String[] args) {//从服务器获得图片保存到本地

saveImageToDisk();

}

}

HTTP-POST(Java接口)方式

public classHttpUtils {//请求服务器端的url

private static String PATH = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";private staticURL url;publicHttpUtils() {//TODO Auto-generated constructor stub

}static{try{

url= newURL(PATH);

}catch(MalformedURLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}/***@paramparams

* 填写的url的参数

*@paramencode

* 字节编码

*@return

*/

public static String sendPostMessage(Mapparams,

String encode) {//作为StringBuffer初始化的字符串

StringBuffer buffer = newStringBuffer();try{if (params != null && !params.isEmpty()) {for (Map.Entryentry : 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) {returnchangeInputStream(urlConnection.getInputStream(), encode);

}

}catch(UnsupportedEncodingException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}return "";

}/*** 将一个输入流转换成指定编码的字符串

*

*@paraminputStream

*@paramencode

*@return

*/

private staticString changeInputStream(InputStream inputStream,

String encode) {//TODO Auto-generated method stub

ByteArrayOutputStream outputStream = newByteArrayOutputStream();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= newString(outputStream.toByteArray(), encode);

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}returnresult;

}/***@paramargs*/

public static voidmain(String[] args) {//TODO Auto-generated method stub

Map params = new HashMap();

params.put("username", "admin");

params.put("password", "1234");

String result= HttpUtils.sendPostMessage(params, "utf-8");

System.out.println("--result->>" +result);

}

}

HTTP-POST(Apache接口)方式

public classHttpUtils {publicHttpUtils() {//TODO Auto-generated constructor stub

}public staticString sendHttpClientPost(String path,

Mapmap, String encode) {

List list = new ArrayList();if (map != null && !map.isEmpty()) {for (Map.Entryentry : map.entrySet()) {

list.add(newBasicNameValuePair(entry.getKey(), entry

.getValue()));

}

}try{//实现将请求的参数封装到表单中,请求体重

UrlEncodedFormEntity entity = newUrlEncodedFormEntity(list, encode);//使用Post方式提交数据

HttpPost httpPost = newHttpPost(path);

httpPost.setEntity(entity);//指定post请求

DefaultHttpClient client = newDefaultHttpClient();

HttpResponse httpResponse=client.execute(httpPost);if (httpResponse.getStatusLine().getStatusCode() == 200) {returnchangeInputStream(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 "";

}/*** 将一个输入流转换成指定编码的字符串

*

*@paraminputStream

*@paramencode

*@return

*/

public staticString changeInputStream(InputStream inputStream,

String encode) {//TODO Auto-generated method stub

ByteArrayOutputStream outputStream = newByteArrayOutputStream();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= newString(outputStream.toByteArray(), encode);

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}returnresult;

}/***@paramargs*/

public static voidmain(String[] args) {//TODO Auto-generated method stub

String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";

Map params = new HashMap();

params.put("username", "admin");

params.put("password", "123");

String result= HttpUtils.sendHttpClientPost(path, params, "utf-8");

System.out.println("-->>"+result);

}

}

java get与post区别_POST和GET区别相关推荐

  1. java中String new和直接赋值的区别

        Java中String new和直接赋值的区别     对于字符串:其对象的引用都是存储在栈中的,如果是编译期已经创建好(直接用双引号定义的)的就存储在常量池中,如果是运行期(new出来的)才 ...

  2. 【Java学习笔记之二十九】Java中的equals和==的用法及区别

    Java中的"equals"和"=="的用法及区别 在初学Java时,可能会经常碰到下面的代码: 1 String str1 = new String(&quo ...

  3. Java中print、printf、println的区别 详解

    Java中print.printf.println的区别详解 printf主要是继承了C语言的printf的一些特性,可以进行格式化输出 print就是一般的标准输出,但是不换行 println和pr ...

  4. java get post 区别详解_[Java教程]GET 与 POST 其实没有什么区别

    [Java教程]GET 与 POST 其实没有什么区别 0 2020-12-30 11:36:20 GET 与 POST 其实没有什么区别 本文写于 2020 年 12 月 30 日 GET 与 PO ...

  5. Java中方法重载和方法重写的区别

    文章目录 1 Java中方法重载和方法重写的区别 1 Java中方法重载和方法重写的区别 主要区别如下: 方法重载: 在同一个类中 方法名相同 参数个数.顺序.类型不同 返回值类型.访问修饰符任意 方 ...

  6. 【Java】泛型中 extends 和 super 的区别?

    <? extends T>和<? super T>是Java泛型中的"通配符(Wildcards)"和"边界(Bounds)"的概念. ...

  7. IEnumeratorTItem和IEnumerator Java 抽象类和普通类、接口的区别——看完你就顿悟了...

    IEnumerable 其原型至少可以说有15年历史,或者更长,它是通过 IEnumerator 来定义的,而后者中使用装箱的 object 方式来定义,也就是弱类型的.弱类型不但会有性能问题,最主要 ...

  8. Java中的LongAdder和AtomicLong有什么区别?

    ● Java中的LongAdder和AtomicLong有什么区别? 考点:JDK 参考回答: JDK1.8引入了LongAdder类.CAS机制就是,在一个死循环内,不断尝试修改目标值,直到修改成功 ...

  9. java自动递增前缀式和后缀式区别

    java自动递增前缀式和后缀式区别 java自动递增(自动递减)前缀式表达式 '++' 操作符位于变量或表达式的前面,而后缀式表达式'++'位于变量或表达式的后面,Example: 前缀式: ++i: ...

  10. php提交表单时判断 if($_POST[submit])与 if(isset($_POST[submit])) 的区别

    if(isset($_POST['submit'])) 它的意思是不是判断是否配置了$_POST['submit'] 这个变量呢?如果有这个变量 在执行其它代码 应该这样用if(isset($_POS ...

最新文章

  1. mysql 数据目录更改
  2. 11 个高效的同行代码评审最佳实践
  3. 1、MySQL日志及分类
  4. Spring-学习笔记07【银行转账案例】
  5. linux shell 脚本 supress,Linux指令和shell脚本
  6. 百度地图标注图标太小
  7. 初识Flink广播变量broadcast
  8. 的watch什么时候触发_Vue中computedamp;methodamp;watch的区别
  9. springmvc线程安全问题
  10. 社会达尔文主义 盛行时间_新达尔文主义的心理理论
  11. 备份手机相册----syncthing (一劳永逸式解决方案)
  12. POPE-NH|1-棕榈酰基-2-油酰基磷脂酰乙醇胺POPE与NHS(N-羟基琥珀酰亚胺)酯偶联物
  13. 黑马程序员Netty全套教程,全网最全Netty深入浅出教程,Java网络编程的王者
  14. 英文格式的时间转换为 yyyy-MM-dd 格式
  15. python的爬虫攻击
  16. 抖音搬运视频热门技巧 剪辑后会修改视频md5
  17. 《流浪星球》作者:区块链让虚拟世界代替现实世界
  18. 提升项目经理谈话能力的十个实用技巧
  19. 十年Java架构师分享
  20. lavarel5.2中多表联查 搜索后分页

热门文章

  1. 苹果Objective-C源代码
  2. GB28181国标错误码整理
  3. protoc 命令 java_protoc 指令介绍
  4. java学习电子书_Java学习指南(第4版)(上册) 中文完整pdf扫描版[179MB]
  5. 极化码理论及算法研究2-什么是极化码?
  6. python3.9.0a2怎么安装pygame_Python自学——pygame安装
  7. 文件在计算机被锁定怎么打开方式,4种删除锁定文件的方法
  8. 基于python 爬虫网络舆情分析系统_基于Python的网络爬虫系统
  9. Smobiler图片二进制上传处理
  10. linux 默认ping的端口,linux的ping命令端口号