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

Web程序:使用GET和POST方法发送请求

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

浏览器打开:

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

关键代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘index.jsp‘ starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    This is 圣骑士Wind‘s page. <br>
    <p>
        以GET方法发送:<br>
    <form action="servlet/WelcomeUserServlet" method="get">
        Username: <input type="text" name="username" value="">
        Age: <input type="text" name="age" value="">
        <input type="submit" value="Submit">
    </form>
    </p>
        <p>
        以POST方法发送:<br>
    <form action="servlet/WelcomeUserServlet" method="post">
        Username: <input type="text" name="username" value="">
        Age: <input type="text" name="age" value="">
        <input type="submit" value="Submit">
    </form>
    </p>
  </body>
</html>
index.jsp显示结果:
package com.shengqishiwind;

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 WelcomeUserServlet extends HttpServlet
{
    /**
     * 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
    {
        process(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
    {
        process(request, response);
    }

    private void process(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String username = request.getParameter("username");
        String age = request.getParameter("age");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html><head><title>Welcome!</title></head>");
        out.println("<body> Welcome my dear friend!<br>");
        out.println("Your name is: " + username + "<br>");
        out.println("And your age is: " + age + "</body></html>");

        out.flush();
        out.close();

    }

}
WelcomeUserServlet

Android程序:使用GET方法和POST方法发送请求

上面是用浏览器访问页面并提交数据,如果想在Android客户端提交,服务器端的代码是不用变的,只要写好客户端代码即可:

首先要在manifest中加上访问网络的权限:

<manifest ... >
    <uses-permission android:name="android.permission.INTERNET" />
    ...
</manifest>

布局文件activity_http_demo2.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Username:" />

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="User Age:" />

    <EditText
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="number" />

    <Button
        android:id="@+id/submit_get"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit using GET" />

    <Button
        android:id="@+id/submit_post"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Submit using POST" />

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#0000FF"
        android:textSize="14sp">
    </TextView>

</LinearLayout>

Activity代码如下:
package com.example.httpdemo2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class HttpDemo2Activity extends Activity
{
    private String TAG = "http";
    private EditText mNameText = null;
    private EditText mAgeText = null;

    private Button getButton = null;
    private Button postButton = null;

    private TextView mResult = null;

    // 基本地址:服务器ip地址:端口号/Web项目逻辑地址+目标页面(Servlet)的url-pattern
    private String baseURL = "http://192.168.11.6:8080/HelloWeb/servlet/WelcomeUserServlet";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        Log.i(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_demo2);

        mNameText = (EditText) findViewById(R.id.name);
        mAgeText = (EditText) findViewById(R.id.age);
        mResult = (TextView) findViewById(R.id.result);

        getButton = (Button) findViewById(R.id.submit_get);
        getButton.setOnClickListener(mGetClickListener);
        postButton = (Button) findViewById(R.id.submit_post);
        postButton.setOnClickListener(mPostClickListener);
    }

    private OnClickListener mGetClickListener = new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            Log.i(TAG, "GET request");
            // 先获取用户名和年龄
            String name = mNameText.getText().toString();
            String age = mAgeText.getText().toString();

            // 使用GET方法发送请求,需要把参数加在URL后面,用?连接,参数之间用&分隔
            String url = baseURL + "?username=" + name + "&age=" + age;

            // 生成请求对象
            HttpGet httpGet = new HttpGet(url);
            HttpClient httpClient = new DefaultHttpClient();

            // 发送请求
            try
            {

                HttpResponse response = httpClient.execute(httpGet);

                // 显示响应
                showResponseResult(response);// 一个私有方法,将响应结果显示出来

            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }
    };

    private OnClickListener mPostClickListener = new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            Log.i(TAG, "POST request");
            // 先获取用户名和年龄
            String name = mNameText.getText().toString();
            String age = mAgeText.getText().toString();

            NameValuePair pair1 = new BasicNameValuePair("username", name);
            NameValuePair pair2 = new BasicNameValuePair("age", age);

            List<NameValuePair> pairList = new ArrayList<NameValuePair>();
            pairList.add(pair1);
            pairList.add(pair2);

            try
            {
                HttpEntity requestHttpEntity = new UrlEncodedFormEntity(
                        pairList);
                // URL使用基本URL即可,其中不需要加参数
                HttpPost httpPost = new HttpPost(baseURL);
                // 将请求体内容加入请求中
                httpPost.setEntity(requestHttpEntity);
                // 需要客户端对象来发送请求
                HttpClient httpClient = new DefaultHttpClient();
                // 发送请求
                HttpResponse response = httpClient.execute(httpPost);
                // 显示响应
                showResponseResult(response);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }
    };

    /**
     * 显示响应结果到命令行和TextView
     * @param response
     */
    private void showResponseResult(HttpResponse response)
    {
        if (null == response)
        {
            return;
        }

        HttpEntity httpEntity = response.getEntity();
        try
        {
            InputStream inputStream = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream));
            String result = "";
            String line = "";
            while (null != (line = reader.readLine()))
            {
                result += line;

            }

            System.out.println(result);
            mResult.setText("Response Content from server: " + result);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

}

可以从中对比GET方法和POST方法的区别:

GET方法需要用?将参数连接在URL后面,各个参数之间用&连接。

POST方法发送请求时,仍然使用基本的URL,将参数信息放在请求实体中发送。

程序运行结果如下:

 
 
				
时间: 2024-08-02 16:45:25

Android HTTP实例 使用GET方法和POST方法发送请求的相关文章

Android中Looper的quit方法和quitSafely方法

Looper是通过调用loop方法驱动着消息循环的进行: 从MessageQueue中阻塞式地取出一个消息,然后让Handler处理该消息,周而复始,loop方法是个死循环方法. 那如何终止消息循环呢?我们可以调用Looper的quit方法或quitSafely方法,二者稍有不同. Looper的quit方法源码如下: public void quit() { mQueue.quit(false); } Looper的quitSafely方法源码如下: public void quitSafel

Android中的Sqlite中的onCreate方法和onUpgrade方法的执行时机

今天在做数据库升级的时候,遇到一个问题,就是onCreate方法和onUpgrade方法的执行时机的问题,这个当时在操作的时候,没有弄清楚,很是迷糊,所以写代码的时候出现了很多的问题,所以没办法就去扒源代码看了.不过在此之前我讲解过一篇关于数据库升级的文章,但是那里没有详细的讲解一下这两个方法的执行时机,所以这里就在单独说一下 关于数据库升级的文章:http://blog.csdn.net/jiangwei0910410003/article/details/39670813 不多说,下面直接进

Android中的Sqlite中的onCreate方法和onUpgrade方法的执行时机--(转)

原文:http://blog.csdn.net/jiangwei0910410003/article/details/46536329 今天在做数据库升级的时候,遇到一个问题,就是onCreate方法和onUpgrade方法的执行时机的问题,这个当时在操作的时候,没有弄清楚,很是迷糊,所以写代码的时候出现了很多的问题,所以没办法就去扒源代码看了.不过在此之前我讲解过一篇关于数据库升级的文章,但是那里没有详细的讲解一下这两个方法的执行时机,所以这里就在单独说一下 关于数据库升级的文章:http:/

详解equals()方法和hashCode()方法

前言 Java的基类Object提供了一些方法,其中equals()方法用于判断两个对象是否相等,hashCode()方法用于计算对象的哈希码.equals()和hashCode()都不是final方法,都可以被重写(overwrite). 本文介绍了2种方法在使用和重写时,一些需要注意的问题. 一.equal()方法 Object类中equals()方法实现如下: public boolean equals(Object obj) { return (this == obj); } 通过该实现

黑马程序员 02-set方法和get方法

———Java培训.Android培训.iOS培训..Net培训.期待与您交流! ——— 1.set方法与get方法的使用场合 @public的成员变量可以被外界随意赋值,往往会产生脏数据,应该使用set方法和get方法来管理成员的访问(类似安检.水龙头过滤,过滤掉不合理的对象),不如人的年龄不可能为负. 2.set方法 (1)作用:给外界提供一个公共的方法用来设置成员变量值,可以在方法里面过滤掉一些不合理的值: (2)命名规范: 1> 方法名必须以set开头 2> set后面跟上成员变量的名

virtual方法和abstract方法

在C#的学习中,容易混淆virtual方法和abstract方法的使用,现在来讨论一下二者的区别.二者都牵涉到在派生类中与override的配合使用. 一.Virtual方法(虚方法) virtual 关键字用于在基类中修饰方法.virtual的使用会有两种情况: 情况1:在基类中定义了virtual方法,但在派生类中没有重写该虚方法.那么在对派生类实例的调用中,该虚方法使用的是基类定义的方法. 情况2:在基类中定义了virtual方法,然后在派生类中使用override重写该方法.那么在对派生

wait方法和sleep方法的区别

一.概念.原理.区别 Java中的多线程是一种抢占式的机制而不是分时机制.线程主要有以下几种状态:可运行,运行,阻塞,死亡.抢占式机制指的是有多个线程处于可运行状态,但是只有一个线程在运行. 当有多个线程访问共享数据的时候,就需要对线程进行同步.线程中的几个主要方法的比较: Thread类的方法:sleep(),yield()等 Object的方法:wait()和notify()等 每个对象都有一个机锁来控制同步访问.Synchronized关键字可以和对象的机锁交互,来实现线程的同步. 由于s

JavaScript中的apply()方法和call()方法使用介绍

javascript中apply和call方法的作用及区别说明 call和apply的说明 call,apply都属于Function.prototype的一个方法,它是JavaScript引擎内在实现的,因为属于Function.prototype,所以每个Function对象实例(就是每个方法)都有call,apply属性.既然作为方法的属性,那它们的使用就当然是针对方法的了,这两个方法是容易混淆的,因为它们的作用一样,只是使用方式不同. 语法:foo.call(this, arg1,arg

基础回顾:get方法和set方法(类的继承多态)

基础回顾:get方法和set方法 定义类成员变量时,可以在@interface中定义,也可以在@implementation中定义: 在@interface中声明,成员变量的状态是受保护的,即“@protected”: 在@implementation中声明,成员变量的状态是私有的,即“@private” 在类的外面,是无法直接访问成员变量的,只有将成员变量修改为@public时,才可以外部访问. 使用@public时,访问成员变量使用“->”,如: time->hour=25; 但使用@pu