设为首页 收藏本站
查看: 1714|回复: 0

[经验分享] 使用Apache HttpClient访问网络(实现手机端注册,服务器返回信息)

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2015-11-9 09:51:38 | 显示全部楼层 |阅读模式
这两天看了点网络编程,根据教程写了一个小的注册服务,贴出来。

本实例分别演示用GET方式和POST方式想服务器发送注册信息,分为客户端和服务器端两部分:
  • 客户端注册用户信息,发送到服务器
  • 服务器端接收信息并向客户端返回注册信息。(服务器端使用J2EE中的Servlet技术来实现,并发布到Tomcat服务器上)



代码运行效果如下:

客户端:
wKiom1Y8f4Hh1cCwAACyV5lkvq8182.jpg

1.点击get注册按钮后:

客户端:
wKioL1Y8f_bBnm2TAADLkOXIZnA462.jpg

服务器端:
wKioL1Y8gDPAeZMFAAGIyl7a8CM386.jpg

2.点击post注册按钮后:

客户端:

wKioL1Y8gG2yxYCtAADLbd3YsIY467.jpg

服务器端:
wKioL1Y8gJyzC4keAAFHgScLq64020.jpg


3.当服务器端关闭时:

wKiom1Y8gIqxSfDhAAFsJE4zB7M972.jpg
客户端注册信息时会提示链接超时:

wKioL1Y8gUSRNCtnAADD-ctGl3E652.jpg



这就是完整的运行图,下面给出完整代码和代码注释:


客户端代码:

1.activity_main.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"
    tools:context=".MainActivity" >

    <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="账户"
                android:layout_marginTop="5.0dip"
                android:layout_marginLeft="5.0dip"
                android:layout_marginRight="5.0dip"
                android:textStyle="bold"
                android:textAppearance="?android:textAppearanceMedium" />

        <EditText android:id="@+id/username"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5.0dip"
                android:layout_marginLeft="5.0dip"
                android:layout_marginRight="5.0dip" />

        <TextView android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="密码"
                android:layout_marginTop="5.0dip"
                android:layout_marginLeft="5.0dip"
                android:layout_marginRight="5.0dip"
                android:textStyle="bold"
                android:textAppearance="?android:textAppearanceMedium" />

        <EditText android:id="@+id/password"
            android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="5.0dip"
                android:layout_marginLeft="5.0dip"
                android:layout_marginRight="5.0dip" />

        <LinearLayout android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">

                <Button android:id="@+id/button_get"
                    android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5.0dip"
                        android:layout_marginLeft="5.0dip"
                        android:layout_marginRight="5.0dip"
                        android:layout_weight="1.0"
                        android:text="get注册" />

                <Button
                    android:id="@+id/button_post"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="5.0dip"
                        android:layout_marginLeft="5.0dip"
                        android:layout_marginRight="5.0dip"
                        android:layout_weight="1.0"
                        android:text="post注册" />

        </LinearLayout>

        <TextView
            android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="服务器返回数据:"
                android:layout_marginTop="5.0dip"
                android:layout_marginLeft="5.0dip"
                android:layout_marginRight="5.0dip"
                android:textStyle="bold"
                android:textAppearance="?android:textAppearanceMedium" />
        <TextView android:id="@+id/response_msg"
            android:layout_width="fill_parent"
                android:layout_height="150dip"
                android:layout_marginTop="5.0dip"
                android:layout_marginLeft="5.0dip"
                android:layout_marginRight="5.0dip"
                android:textStyle="bold"
                android:textAppearance="?android:textAppearanceMedium" />

</LinearLayout>



2.MainActivity.java代码:

public class MainActivity extends Activity {

        private static final String SERVER_ADDRESS = "http://10.248.27.195:8080/HttpServer/UserRegisterServer";

        private EditText username;
        private EditText password;
        private Button getMetond;
        private Button postMethod;
        private TextView responseMessage;
        Handler handler=new Handler(){
                public void handleMessage(android.os.Message msg) {
                         if(msg.what==0x101){
                                        Bundle bundle=msg.getData();
                                    String responseMsg = bundle.getString("msg");
                                    responseMessage.setText(responseMsg);
                                }
                }
        };
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                // 初始化控件
                username = (EditText) findViewById(R.id.username);
                password = (EditText) findViewById(R.id.password);
                getMetond = (Button) findViewById(R.id.button_get);
                postMethod = (Button) findViewById(R.id.button_post);
                responseMessage = (TextView) findViewById(R.id.response_msg);
                responseMessage.setBackgroundColor(Color.BLACK);
                responseMessage.setTextColor(Color.WHITE);

                getMetond.setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                                registerByGetRequest();
                        }
                });
                // 注册"以GET方式注册"按钮事件监听器,以GET方式发送数据,并显示服务器返回结果

                postMethod.setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {

                                registerByPostRequest();
                        }
                });
        }
           // 注册"以POST方式注册"按钮事件监听器, 以POST方式发送数据,并显示服务器返回结果


        /**
         * 以GET请求方式与服务器进行通信
         */
        private void registerByGetRequest() {
                new Thread(new Runnable() {

                        public void run() {
                                // TODO Auto-generated method stub
                                Message m=new Message();
                                m.what=0x101;
                                Bundle bundle=new Bundle();
                                try {
                                        String url = new StringBuffer(SERVER_ADDRESS).append("?un=")
                                                        .append(username.getText().toString().trim())
                                                        .append("&pwd=")
                                                        .append(password.getText().toString().trim())
                                                        .toString();
                                        HttpClient httpClient = new DefaultHttpClient();
                                        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
                        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000    );
                        //超时操作
                                        HttpGet httpGetRequest = new HttpGet(url);
                                        HttpResponse response = httpClient.execute(httpGetRequest);
                                        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode())
                                        {
                                                String responseMsg = "Get方式注册信息\n"+EntityUtils.toString(response.getEntity());
                                                bundle.putString("msg",responseMsg);
                                                m.setData(bundle);
                                                handler.sendMessage(m);
                                        }else{
                                                String errorMsg = "错误";
                                                bundle.putString("msg",errorMsg);
                                                m.setData(bundle);
                                                handler.sendMessage(m);
                                        }

                                }catch (ClientProtocolException e) {
                                        e.printStackTrace();
                                } catch (IOException e) {
                                        bundle.putString("msg","链接服务器超时");
                        m.setData(bundle);
                        handler.sendMessage(m);
                                        e.printStackTrace();
                                }

                        }
                }).start();

        }

        /**
         * 以POST请求方式与服务器进行通信
         */
        private void registerByPostRequest() {

        new Thread(new Runnable() {
                        public void run() {
                                // TODO Auto-generated method stub
                                Message m=new Message();
                                m.what=0x101;
                                Bundle bundle=new Bundle();
                                try {

                                        HttpClient httpClient = new DefaultHttpClient();
                                        //初始化HttpClient对象
                                        HttpPost httpPostRequest = new HttpPost(SERVER_ADDRESS);
                                        //创建HttpPost链接
                                        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
                        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000    );
                        //超时操作
                                        List<NameValuePair> paramList = new ArrayList<NameValuePair>();

                                        BasicNameValuePair userNameParam = new BasicNameValuePair("un", username.getText().toString().trim());
                                        BasicNameValuePair emailParam = new BasicNameValuePair("pwd", password.getText().toString().trim());
                                        paramList.add(userNameParam);
                                        paramList.add(emailParam);
                                        //数据处理

                                        HttpEntity httpEntity = new UrlEncodedFormEntity(paramList, HTTP.UTF_8);
                                        //对数据进行编码
                                        httpPostRequest.setHeader("content-type", "text/html");
                                        //设置数据类型
                                        httpPostRequest.setEntity(httpEntity);       
                                        //向服务器发送HttpPost请求
                                        HttpResponse response = httpClient.execute(httpPostRequest);
                                        //读取服务器返回的数据
                                        if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
                                                String responseMsg = "Post注册信息\n"+EntityUtils.toString(response.getEntity());
                                                bundle.putString("msg",responseMsg);
                                                m.setData(bundle);
                                                handler.sendMessage(m);
                                        }else{
                                                String errorMsg = "错误:" + response.getStatusLine().toString();
                                                bundle.putString("msg",errorMsg);
                                                m.setData(bundle);
                                                handler.sendMessage(m);
                                        }
                                } catch (ClientProtocolException e) {
                                        e.printStackTrace();
                                } catch (IOException e) {
                        bundle.putString("msg","链接服务器超时");
                        m.setData(bundle);
                        handler.sendMessage(m);
                                        e.printStackTrace();
                                }
                        }
                }).start();
        }
}



服务器端:

UserRegisterServer.java代码:

public class UserRegisterServer extends HttpServlet {
        private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserRegisterServer() {
        super();
    }

        /**
         * 当请求为HTTP GET时执行此方法
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                String userName = request.getParameter("un");
                String password = request.getParameter("pwd");


                if(userName!=""&&password!=""&&userName!=null&&password!=null){
                        System.out.println("Get方式用户注册信息:\n");
                        System.out.println("用户名:" + userName);
                        System.out.println("邮箱: " + password);
                    response.getWriter().print("Register Success!\nID = " + generateUserId());
                 // 向客户端发送数据
                }
                else{
                        System.out.println("用户名或邮箱不正确");
                        response.getWriter().print("UserName ERROR or Email ERROR!");       
                }
        }

        /**
         * 当请求为HTTP POST时执行此方法
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                // 读取从客户端发送来的数据
                BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String data = null;
        StringBuilder sb = new StringBuilder();
        while((data = br.readLine())!=null){
            sb.append(data);
        }

        String temp = URLDecoder.decode(sb.toString(), "utf-8");
        // 对数据进行解码操作
        System.out.println("Post方式用户注册信息:\n " + temp);
        response.getWriter().print("Register Success!\nID = " + generateUserId());
                // 向客户端发送数据
        }

        /**
         * 生成随机数代表当前注册用户ID
         * @return
         */
        private String generateUserId(){
                Random ran = new Random();
                return String.valueOf(Math.abs(ran.nextInt()));
        }
}


这就是完整的代码了,其中get方式和post方式的区别:
1. get是从服务器上获取数据,post是向服务器传送数据。2. get是把参数数据队列加到提交表单的ACTION属性所指的URL中,值和表单内各个字段一一对应,在URL中可以看到。post是通过HTTP post机制,将表单内各个字段与其内容放置在HTML HEADER内一起传送到ACTION属性所指的URL地址。用户看不到这个过程。3. 对于get方式,用Request.QueryString获取变量的值,对于post方式,用Request.Form获取提交的数据。4. get传送的数据量较小,不能大于2KB。post传送的数据量较大,一般被默认为不受限制。但理论上,IIS4中最大量为80KB,IIS5中为100KB。5. get安全性非常低,post安全性较高。但是执行效率却比Post方法好。 建议:1、get方式的安全性较Post方式要差些,包含机密信息的话,建议用Post数据提交方式;2、在做数据查询时,建议用Get方式;而在做数据添加、修改或删除时,建议用Post方式;

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-136881-1-1.html 上篇帖子: apache配置httpd-vhosts 下篇帖子: linux apache服务器配置虚拟主机 服务器 手机 网络 信息
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

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