Maison  >  Article  >  php教程  >  php开发app接口之android端的简易实现

php开发app接口之android端的简易实现

WBOY
WBOYoriginal
2016-06-06 19:42:181229parcourir

对于很多新手来说,如何 实现 android端与服务器之间的通信还是一个难题。这里我提供一个比较好用的类 package org.crazyit.net; import java.io.*; import java.net.*; import java.util.*; /** * Description: * br/site: a href="http://www.crazyit.org"

对于很多新手来说,如何实现android端与服务器之间的通信还是一个难题。这里我提供一个比较好用的类

<code><span>package</span> org.crazyit.net;

<span>import</span> java.io.*; 
<span>import</span> java.net.*;
<span>import</span> java.util.*;

<span>/**
 * Description:
 * <br>site: <a href="http://www.crazyit.org">crazyit.org</a>
 * <br>Copyright (C), 2001-2014, Yeeku.H.Lee
 * <br>This program is protected by copyright laws.
 * <br>Program Name:
 * <br>Date:
 *<span> @author</span>  Yeeku.H.Lee kongyeeku@163.com
 *<span> @version</span>  1.0
 */</span>
<span>public</span> <span><span>class</span> <span>GetPostUtil</span>
{</span>
    <span>/**
     * 向指定URL发送GET方法的请求
     *<span> @param</span> url 发送请求的URL
     *<span> @param</span> params 请求参数,请求参数应该是name1=value1&name2=value2的形式。
     *<span> @return</span> URL所代表远程资源的响应
     */</span>
    <span>public</span> <span>static</span> String <span>sendGet</span>(String url, String params)
    {
        String result = <span>""</span>;
        BufferedReader in = <span>null</span>;
        <span>try</span>
        {
            String urlName = url + <span>"?"</span> + params;
            URL realUrl = <span>new</span> URL(urlName);
            <span>// 打开和URL之间的连接</span>
            URLConnection conn = realUrl.openConnection();
            <span>// 设置通用的请求属性</span>
            conn.setRequestProperty(<span>"accept"</span>, <span>"*/*"</span>);
            conn.setRequestProperty(<span>"connection"</span>, <span>"Keep-Alive"</span>);
            conn.setRequestProperty(<span>"user-agent"</span>,
                <span>"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"</span>);
            <span>// 建立实际的连接</span>
            conn.connect();  <span>//①</span>
            <span>// 获取所有响应头字段</span>
            Map<string list>> map = conn.getHeaderFields();
            <span>// 遍历所有的响应头字段</span>
            <span>for</span> (String key : map.keySet())
            {
                System.out.println(key + <span>"--->"</span> + map.get(key));
            }
            <span>// 定义BufferedReader输入流来读取URL的响应</span>
            in = <span>new</span> BufferedReader(
                <span>new</span> InputStreamReader(conn.getInputStream()));
            String line;
            <span>while</span> ((line = in.readLine()) != <span>null</span>)
            {
                result += <span>"\n"</span> + line;
            }
        }
        <span>catch</span> (Exception e)
        {
            System.out.println(<span>"发送GET请求出现异常!"</span> + e);
            e.printStackTrace();
        }
        <span>// 使用finally块来关闭输入流</span>
        <span>finally</span>
        {
            <span>try</span>
            {
                <span>if</span> (in != <span>null</span>)
                {
                    in.close();
                }
            }
            <span>catch</span> (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        <span>return</span> result;
    }

    <span>/**
     * 向指定URL发送POST方法的请求
     *<span> @param</span> url 发送请求的URL
     *<span> @param</span> params 请求参数,请求参数应该是name1=value1&name2=value2的形式。
     *<span> @return</span> URL所代表远程资源的响应
     */</span>
    <span>public</span> <span>static</span> String <span>sendPost</span>(String url, String params)
    {
        PrintWriter out = <span>null</span>;
        BufferedReader in = <span>null</span>;
        String result = <span>""</span>;
        <span>try</span>
        {
            URL realUrl = <span>new</span> URL(url);
            <span>// 打开和URL之间的连接</span>
            URLConnection conn = realUrl.openConnection();
            <span>// 设置通用的请求属性</span>
            conn.setRequestProperty(<span>"accept"</span>, <span>"*/*"</span>);
            conn.setRequestProperty(<span>"connection"</span>, <span>"Keep-Alive"</span>);
            conn.setRequestProperty(<span>"user-agent"</span>,
                <span>"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"</span>);
            <span>// 发送POST请求必须设置如下两行</span>
            conn.setDoOutput(<span>true</span>);
            conn.setDoInput(<span>true</span>);
            <span>// 获取URLConnection对象对应的输出流</span>
            out = <span>new</span> PrintWriter(conn.getOutputStream());
            <span>// 发送请求参数</span>
            out.print(params);  <span>//②</span>
            <span>// flush输出流的缓冲</span>
            out.flush();
            <span>// 定义BufferedReader输入流来读取URL的响应</span>
            in = <span>new</span> BufferedReader(
                <span>new</span> InputStreamReader(conn.getInputStream()));
            String line;
            <span>while</span> ((line = in.readLine()) != <span>null</span>)
            {
                result += <span>"\n"</span> + line;
            }
        }
        <span>catch</span> (Exception e)
        {
            System.out.println(<span>"发送POST请求出现异常!"</span> + e);
            e.printStackTrace();
        }
        <span>// 使用finally块来关闭输出流、输入流</span>
        <span>finally</span>
        {
            <span>try</span>
            {
                <span>if</span> (out != <span>null</span>)
                {
                    out.close();
                }
                <span>if</span> (in != <span>null</span>)
                {
                    in.close();
                }
            }
            <span>catch</span> (IOException ex)
            {
                ex.printStackTrace();
            }
        }
        <span>return</span> result;
    }
}
</string></code>

在这里我们简单的做一个android的客户端

<code>这里是layout里的布局文件
<span><?xml version="1.0" encoding="utf-8"?></span>
<span>LinearLayout</span> <span>xmlns:android</span>=<span>"http://schemas.android.com/apk/res/android"</span>
    <span>android:orientation</span>=<span>"vertical"</span>
    <span>android:layout_width</span>=<span>"fill_parent"</span>
    <span>android:layout_height</span>=<span>"fill_parent"</span>
    >
<span>LinearLayout
</span>    <span>android:orientation</span>=<span>"horizontal"</span>
    <span>android:layout_width</span>=<span>"fill_parent"</span>
    <span>android:layout_height</span>=<span>"wrap_content"</span>
    <span>android:gravity</span>=<span>"center"</span>
    >
<span>Button
</span>    <span>android:id</span>=<span>"@+id/get"</span>  
    <span>android:layout_width</span>=<span>"wrap_content"</span> 
    <span>android:layout_height</span>=<span>"wrap_content"</span> 
    <span>android:text</span>=<span>"@string/get"</span>
    />
<span>Button
</span>    <span>android:id</span>=<span>"@+id/post"</span>  
    <span>android:layout_width</span>=<span>"wrap_content"</span> 
    <span>android:layout_height</span>=<span>"wrap_content"</span> 
    <span>android:text</span>=<span>"@string/post"</span>
    />      
<span><span>LinearLayout</span>></span> 
<span>TextView</span>  
    <span>android:id</span>=<span>"@+id/show"</span>
    <span>android:layout_width</span>=<span>"fill_parent"</span> 
    <span>android:layout_height</span>=<span>"fill_parent"</span> 
    <span>android:gravity</span>=<span>"top"</span>
    <span>android:background</span>=<span>"#ffff"</span>
    <span>android:textColor</span>=<span>"#f000"</span>
    <span>android:textSize</span>=<span>"16dp"</span>
    />
<span><span>LinearLayout</span>></span>
</code>

这里我们简单的写一下MainActivity

<code><span>package</span> org.crazyit.net;

<span>import</span> android.app.Activity;
<span>import</span> android.os.Bundle;
<span>import</span> android.os.Handler;
<span>import</span> android.os.Message;
<span>import</span> android.view.View;
<span>import</span> android.view.View.OnClickListener;
<span>import</span> android.widget.Button;
<span>import</span> android.widget.EditText;
<span>import</span> android.widget.TextView;

<span>/**
 * Description:
 * <br>site: <a href="http://www.crazyit.org">crazyit.org</a>
 * <br>Copyright (C), 2001-2014, Yeeku.H.Lee
 * <br>This program is protected by copyright laws.
 * <br>Program Name:
 * <br>Date:
 *<span> @author</span>  Yeeku.H.Lee kongyeeku@163.com
 *<span> @version</span>  1.0
 */</span>
<span>public</span> <span><span>class</span> <span>GetPostMain</span> <span>extends</span> <span>Activity</span>
{</span>
    Button get , post;
    TextView show;
    <span>// 代表服务器响应的字符串</span>
    String response;
    Handler handler = <span>new</span> Handler()
    {
        <span>@Override</span>
        <span>public</span> <span>void</span> <span>handleMessage</span>(Message msg)
        {
            <span>if</span>(msg.what == <span>0x123</span>)
            {
                <span>// 设置show组件显示服务器响应</span>
                show.setText(response);
            }
        }
    };
    <span>@Override</span>
    <span>public</span> <span>void</span> <span>onCreate</span>(Bundle savedInstanceState)
    {
        <span>super</span>.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        get = (Button) findViewById(R.id.get);
        post = (Button) findViewById(R.id.post);
        show = (TextView)findViewById(R.id.show);
        get.setOnClickListener(<span>new</span> OnClickListener()
        {
            <span>@Override</span>
            <span>public</span> <span>void</span> <span>onClick</span>(View v)
            {
                <span>new</span> Thread()
                {
                    <span>@Override</span>
                    <span>public</span> <span>void</span> <span>run</span>()
                    {
                        response = GetPostUtil.sendGet(
                            <span>"http://192.168.0.102/test/index.php"</span>
                            , <span>null</span>);
                        <span>// 发送消息通知UI线程更新UI组件</span>
                        handler.sendEmptyMessage(<span>0x123</span>);
                    }
                }.start();
            }
        });
        post.setOnClickListener(<span>new</span> OnClickListener()
        {
            <span>@Override</span>
            <span>public</span> <span>void</span> <span>onClick</span>(View v)
            {
                <span>new</span> Thread()
                {
                    <span>@Override</span>
                    <span>public</span> <span>void</span> <span>run</span>()
                    {
                        response = GetPostUtil.sendPost(
                            <span>"http://192.168.0.102/test/index.php"</span>
                            , <span>"name=帅&pass=leegang"</span>);
                    }
                }.start();
                <span>// 发送消息通知UI线程更新UI组件</span>
                handler.sendEmptyMessage(<span>0x123</span>);
            }
        });
    }
}</code>

php测试的部分很简单,只有一个页面

<code><span><span><?php </span>
header(<span>"content-type:text/html;charset=utf-8"</span>);
<span>echo</span> <span>"hellow world"</span>;
<span>echo</span> <span>$_POST</span>[<span>'name'</span>];</span></span></code>

对于很多新手来说,echo的作用像是c语言中的printf一样,事实上echo最重要的作用是把服务器产生的结果返回回来。

这里是效果图
php开发app接口之android端的简易实现

发送post请求后:
php开发app接口之android端的简易实现
这样简单的说明就完成了。

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn