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

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

 博客源地址:http://www.cnblogs.com/mengdd/p/3142442.html

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

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

  用浏览器打开:

 

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

 

  关键代码如下:

index.jsp

  第二个页面显示结果:

WelcomeUserServlet

 

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

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

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

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

   布局文件:

activity_http_demo2.xml

主要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,将参数信息放在请求实体中发送。

  关于这点的讨论也可以查看本博客其他文章:

  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

猜你喜欢

转载自blog.csdn.net/lintianlin/article/details/49559659
今日推荐