Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 720|回复: 0

[默认分类] Android HTTP实例 使用GET方法和POST方法发送请求

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-7-12 16:28:58 | 显示全部楼层 |阅读模式

    Android HTTP实例 使用GET方法和POST方法发送请求

    Web程序:使用GET和POST方法发送请求
      首先利用MyEclispe+Tomcat写好一个Web程序,实现的功能就是提交用户信息:用户名和年龄,使用GET和POST两种提交方式。
      用浏览器打开:

      不管以哪一种方式,提交以后显示如下页面,将提交的信息再显示出来。

      关键代码如下:




    1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    2. <%
    3. String path = request.getContextPath();
    4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    5. %>
    6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    7. <html>
    8.   <head>
    9.     <base href="<%=basePath%>">
    10.    
    11.     <title>My JSP "index.jsp" starting page</title>
    12.     <meta http-equiv="pragma" content="no-cache">
    13.     <meta http-equiv="cache-control" content="no-cache">
    14.     <meta http-equiv="expires" content="0">   
    15.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    16.     <meta http-equiv="description" content="This is my page">
    17.     <!--
    18.     <link rel="stylesheet" type="text/css" href="styles.css">
    19.     -->
    20.   </head>
    21.   
    22.   <body>
    23.     This is 圣骑士Wind"s page. <br>
    24.     <p>
    25.         以GET方法发送:<br>
    26.     <form action="servlet/WelcomeUserServlet" method="get">
    27.         Username: <input type="text" name="username" value="">
    28.         Age: <input type="text" name="age" value="">
    29.         <input type="submit" value="Submit">
    30.     </form>
    31.     </p>
    32.         <p>
    33.         以POST方法发送:<br>
    34.     <form action="servlet/WelcomeUserServlet" method="post">
    35.         Username: <input type="text" name="username" value="">
    36.         Age: <input type="text" name="age" value="">
    37.         <input type="submit" value="Submit">
    38.     </form>
    39.     </p>
    40.   </body>
    41. </html>
    复制代码

    index.jsp

      第二个页面显示结果:




    1. package com.shengqishiwind;
    2. import java.io.IOException;
    3. import java.io.PrintWriter;
    4. import javax.servlet.ServletException;
    5. import javax.servlet.http.HttpServlet;
    6. import javax.servlet.http.HttpServletRequest;
    7. import javax.servlet.http.HttpServletResponse;
    8. public class WelcomeUserServlet extends HttpServlet
    9. {
    10.     /**
    11.      * The doGet method of the servlet. <br>
    12.      *
    13.      * This method is called when a form has its tag value method equals to get.
    14.      *
    15.      * @param request the request send by the client to the server
    16.      * @param response the response send by the server to the client
    17.      * @throws ServletException if an error occurred
    18.      * @throws IOException if an error occurred
    19.      */
    20.     public void doGet(HttpServletRequest request, HttpServletResponse response)
    21.             throws ServletException, IOException
    22.     {
    23.         process(request, response);
    24.     }
    25.     /**
    26.      * The doPost method of the servlet. <br>
    27.      *
    28.      * This method is called when a form has its tag value method equals to post.
    29.      *
    30.      * @param request the request send by the client to the server
    31.      * @param response the response send by the server to the client
    32.      * @throws ServletException if an error occurred
    33.      * @throws IOException if an error occurred
    34.      */
    35.     public void doPost(HttpServletRequest request, HttpServletResponse response)
    36.             throws ServletException, IOException
    37.     {
    38.         process(request, response);
    39.     }
    40.    
    41.     private void process(HttpServletRequest request, HttpServletResponse response)
    42.             throws ServletException, IOException
    43.     {
    44.         String username = request.getParameter("username");
    45.         String age = request.getParameter("age");
    46.         
    47.         response.setContentType("text/html");
    48.         PrintWriter out = response.getWriter();
    49.         
    50.         out.println("<html><head><title>Welcome!</title></head>");
    51.         out.println("<body> Welcome my dear friend!<br>");
    52.         out.println("Your name is: " + username + "<br>");
    53.         out.println("And your age is: " + age + "</body></html>");
    54.         
    55.         out.flush();
    56.         out.close();
    57.         
    58.     }
    59. }
    复制代码

    WelcomeUserServlet



    Android程序:使用GET方法和POST方法发送请求
      上面是用浏览器访问页面并提交数据,如果想在Android客户端提交,服务器端的代码是不用变的,只要写好客户端代码即可:
      首先要在manifest中加上访问网络的权限:

    1. <manifest ... >
    2.     <uses-permission android:name="android.permission.INTERNET" />
    3. ...
    4. </manifest>
    复制代码

      布局文件:




    1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    2.     xmlns:tools="http://schemas.android.com/tools"
    3.     android:layout_width="match_parent"
    4.     android:layout_height="match_parent"
    5.     android:orientation="vertical" >
    6.     <TextView
    7.         android:layout_width="match_parent"
    8.         android:layout_height="wrap_content"
    9.         android:text="Username:" />
    10.     <EditText
    11.         android:id="@+id/name"
    12.         android:layout_width="match_parent"
    13.         android:layout_height="wrap_content"
    14.         android:inputType="text" />
    15.     <TextView
    16.         android:layout_width="match_parent"
    17.         android:layout_height="wrap_content"
    18.         android:text="User Age:" />
    19.     <EditText
    20.         android:id="@+id/age"
    21.         android:layout_width="match_parent"
    22.         android:layout_height="wrap_content"
    23.         android:inputType="number" />
    24.     <Button
    25.         android:id="@+id/submit_get"
    26.         android:layout_width="match_parent"
    27.         android:layout_height="wrap_content"
    28.         android:text="Submit using GET" />
    29.     <Button
    30.         android:id="@+id/submit_post"
    31.         android:layout_width="match_parent"
    32.         android:layout_height="wrap_content"
    33.         android:text="Submit using POST" />
    34.     <TextView
    35.         android:id="@+id/result"
    36.         android:layout_width="match_parent"
    37.         android:layout_height="wrap_content"
    38.         android:textColor="#0000FF"
    39.         android:textSize="14sp">
    40.     </TextView>
    41. </LinearLayout>
    复制代码

    activity_http_demo2.xml


    主要Activity代码如下:

    1. package com.example.httpdemo2;
    2. import java.io.BufferedReader;
    3. import java.io.IOException;
    4. import java.io.InputStream;
    5. import java.io.InputStreamReader;
    6. import java.io.UnsupportedEncodingException;
    7. import java.util.ArrayList;
    8. import java.util.List;
    9. import org.apache.http.HttpEntity;
    10. import org.apache.http.HttpResponse;
    11. import org.apache.http.NameValuePair;
    12. import org.apache.http.client.HttpClient;
    13. import org.apache.http.client.entity.UrlEncodedFormEntity;
    14. import org.apache.http.client.methods.HttpGet;
    15. import org.apache.http.client.methods.HttpPost;
    16. import org.apache.http.impl.client.DefaultHttpClient;
    17. import org.apache.http.message.BasicNameValuePair;
    18. import android.os.Bundle;
    19. import android.app.Activity;
    20. import android.util.Log;
    21. import android.view.Menu;
    22. import android.view.View;
    23. import android.view.View.OnClickListener;
    24. import android.widget.Button;
    25. import android.widget.EditText;
    26. import android.widget.TextView;
    27. public class HttpDemo2Activity extends Activity
    28. {
    29.     private String TAG = "http";
    30.     private EditText mNameText = null;
    31.     private EditText mAgeText = null;
    32.     private Button getButton = null;
    33.     private Button postButton = null;
    34.     private TextView mResult = null;
    35.     // 基本地址:服务器ip地址:端口号/Web项目逻辑地址+目标页面(Servlet)的url-pattern
    36.     private String baseURL = "http://192.168.11.6:8080/HelloWeb/servlet/WelcomeUserServlet";
    37.     @Override
    38.     protected void onCreate(Bundle savedInstanceState)
    39.     {
    40.         Log.i(TAG, "onCreate");
    41.         super.onCreate(savedInstanceState);
    42.         setContentView(R.layout.activity_http_demo2);
    43.         mNameText = (EditText) findViewById(R.id.name);
    44.         mAgeText = (EditText) findViewById(R.id.age);
    45.         mResult = (TextView) findViewById(R.id.result);
    46.         getButton = (Button) findViewById(R.id.submit_get);
    47.         getButton.setOnClickListener(mGetClickListener);
    48.         postButton = (Button) findViewById(R.id.submit_post);
    49.         postButton.setOnClickListener(mPostClickListener);
    50.     }
    51.     private OnClickListener mGetClickListener = new View.OnClickListener()
    52.     {
    53.         @Override
    54.         public void onClick(View v)
    55.         {
    56.             Log.i(TAG, "GET request");
    57.             // 先获取用户名和年龄
    58.             String name = mNameText.getText().toString();
    59.             String age = mAgeText.getText().toString();
    60.             // 使用GET方法发送请求,需要把参数加在URL后面,用?连接,参数之间用&分隔
    61.             String url = baseURL + "?username=" + name + "&age=" + age;
    62.             // 生成请求对象
    63.             HttpGet httpGet = new HttpGet(url);
    64.             HttpClient httpClient = new DefaultHttpClient();
    65.             // 发送请求
    66.             try
    67.             {
    68.                 HttpResponse response = httpClient.execute(httpGet);
    69.                 // 显示响应
    70.                 showResponseResult(response);// 一个私有方法,将响应结果显示出来
    71.             }
    72.             catch (Exception e)
    73.             {
    74.                 e.printStackTrace();
    75.             }
    76.         }
    77.     };
    78.     private OnClickListener mPostClickListener = new View.OnClickListener()
    79.     {
    80.         @Override
    81.         public void onClick(View v)
    82.         {
    83.             Log.i(TAG, "POST request");
    84.             // 先获取用户名和年龄
    85.             String name = mNameText.getText().toString();
    86.             String age = mAgeText.getText().toString();
    87.             NameValuePair pair1 = new BasicNameValuePair("username", name);
    88.             NameValuePair pair2 = new BasicNameValuePair("age", age);
    89.             List<NameValuePair> pairList = new ArrayList<NameValuePair>();
    90.             pairList.add(pair1);
    91.             pairList.add(pair2);
    92.             try
    93.             {
    94.                 HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
    95.                         pairList);
    96.                 // URL使用基本URL即可,其中不需要加参数
    97.                 HttpPost httpPost = new HttpPost(baseURL);
    98.                 // 将请求体内容加入请求中
    99.                 httpPost.setEntity(requestHttpEntity);
    100.                 // 需要客户端对象来发送请求
    101.                 HttpClient httpClient = new DefaultHttpClient();
    102.                 // 发送请求
    103.                 HttpResponse response = httpClient.execute(httpPost);
    104.                 // 显示响应
    105.                 showResponseResult(response);
    106.             }
    107.             catch (Exception e)
    108.             {
    109.                 e.printStackTrace();
    110.             }
    111.         }
    112.     };
    113.     /**
    114.      * 显示响应结果到命令行和TextView
    115.      * @param response
    116.      */
    117.     private void showResponseResult(HttpResponse response)
    118.     {
    119.         if (null == response)
    120.         {
    121.             return;
    122.         }
    123.         HttpEntity httpEntity = response.getEntity();
    124.         try
    125.         {
    126.             InputStream inputStream = httpEntity.getContent();
    127.             BufferedReader reader = new BufferedReader(new InputStreamReader(
    128.                     inputStream));
    129.             String result = "";
    130.             String line = "";
    131.             while (null != (line = reader.readLine()))
    132.             {
    133.                 result += line;
    134.             }
    135.             System.out.println(result);
    136.             mResult.setText("Response Content from server: " + result);
    137.         }
    138.         catch (Exception e)
    139.         {
    140.             e.printStackTrace();
    141.         }
    142.     }
    143. }
    复制代码

      可以从中对比GET方法和POST方法的区别:
      GET方法需要用?将参数连接在URL后面,各个参数之间用&连接。
      POST方法发送请求时,仍然使用基本的URL,将参数信息放在请求实体中发送。
      关于这点的讨论也可以查看本博客其他文章:
      http://www.cnblogs.com/mengdd/archive/2013/05/26/3099776.html
      http://www.cnblogs.com/mengdd/archive/2013/06/12/3132702.html
      
      程序运行结果如下:


    参考资料
      Android开发视频教程HTTP操作。——http://www.marsdroid.org
      Android Reference: package org.apache.http:
      http://developer.android.com/reference/org/apache/http/package-summary.html

      之前文章中,关于GET和POST的更多讨论:
      http://www.cnblogs.com/mengdd/archive/2013/05/26/3099776.html
      http://www.cnblogs.com/mengdd/archive/2013/06/12/3132702.html
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-18 16:55 , Processed in 0.414620 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表