Android课程---远程服务器存储

在使用Volley进行获取数据时,需要事先准备环境:在libs里面导入一个Volley.jar包,在网上都有,可以下载下来导入,或者自己电脑上有DT的,自己合成一个包也行。

WebActivity.java

package com.hanqi.test5;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class WebActivity extends AppCompatActivity {

    EditText et_w5;
    EditText et_w6;

    RequestQueue requestQueue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);

        et_w5 = (EditText)findViewById(R.id.et_w5);
        et_w5.setText("http://192.168.0.122:8080/TestWeb/index.jsp");

        et_w6 = (EditText)findViewById(R.id.et_w6);

        //获取Volley的请求队列
        requestQueue = Volley.newRequestQueue(this);
    }
    public void getonclick(View view)
    {
        //1.
    /*
     * 使用httpUrlConnection提交get请求
     */
    /*
        1. 显示ProgressDialog
        2. 启动分线程
        3. 在分线程, 发送请求, 得到响应数据
            1). 得到path, 并带上参数name=Tom1&age=11
            2). 创建URL对象
            3). 打开连接, 得到HttpURLConnection对象
            4). 设置请求方式,连接超时, 读取数据超时
            5). 连接服务器
            6). 发请求, 得到响应数据
                得到响应码, 必须是200才读取
                得到InputStream, 并读取成String
            7). 断开连接
        4. 在主线程, 显示得到的结果, 移除dialog
     */
        //1. 显示ProgressDialog
        final ProgressDialog progressDialog = ProgressDialog.show(this,null,"正在请求中...");

        //2. 访问网络 开启子线程

        new Thread()
        {
            @Override
            public void run() {

                try {

                    //1.URl
                    URL url = new URL(et_w5.getText().toString()+"?name=tom");

                    //2.获取连接
                    HttpURLConnection huc = (HttpURLConnection)url.openConnection();

                    //3.请求方式
                    huc.setRequestMethod("GET");
                    //设置超时
                    huc.setConnectTimeout(3000);
                    huc.setReadTimeout(3000);

                    //连接并发送请求
                    huc.connect();

                    //接收
                    //判断返回状态 200
                    int code = huc.getResponseCode();

                    if (code == 200)
                    {
                        //接收数据

                        //输入流
                        InputStream is = huc.getInputStream();
                        //读取流
                        //1- byte数组
                        byte[] b = new byte[1024];
                        //2- 读到数组的长度
                        int i=0;
                        //3.接收到的数据
                        final StringBuilder sbl = new StringBuilder();

                        //边读边写
                        while((i=is.read(b))>0)
                        {
                            sbl.append(new String(b,0,i));
                        }
                        //释放资源
                        is.close();
                        huc.disconnect();

                        //通过主线程显示信息和关闭对话框
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_w6.setText(sbl);

                                //关闭对话框
                                progressDialog.dismiss();
                            }
                        });

                    }
                    else
                    {
                        Toast.makeText(WebActivity.this, "连接错误,返回的状态码= " + code, Toast.LENGTH_SHORT).show();
                    }

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

                super.run();
            }
        }.start();

    }

    public void postonclick(View view)
    {

        //1. 显示ProgressDialog 进度对话框
        final ProgressDialog dialog = ProgressDialog.show(this, null, "正在加载中,请稍后...");
        //2.开启子线程 访问网络
        new Thread()
        {
            public void run()
            {
                try
                {
                    //1) -URL
                    URL url = new URL(et_w5.getText().toString());
                    //2) -URL获取连接
                    HttpURLConnection huc =(HttpURLConnection)url.openConnection();

                    //请求方式
                    huc.setRequestMethod("POST");
                    //设置超时
                    huc.setConnectTimeout(3000);
                    huc.setReadTimeout(3000);


                    //连接并发送请求
                    huc.connect();

                    //用输出流设置请求体
                    OutputStream os = huc.getOutputStream();

                    String str = "name=rose";
                    os.write(str.getBytes("UTF-8"));

                    //接收:
                    //判断返回状态码 200
                    int code = huc.getResponseCode();

                    if (code == 200)
                    {
                        //接收数据

                        //输入流:
                        InputStream is = huc.getInputStream();

                        //读取流
                        //1-byte数组
                        byte[] b = new byte[1024];
                        //2-读到的长度
                        int i = 0;
                        //3-接收到的数据
                        final StringBuilder sbl = new StringBuilder();

                        while ((i = is.read(b))>0)
                        {
                            sbl.append(new String(b,0,i));
                        }
                        //释放资源
                        is.close();
                        huc.disconnect();

                        //通过主线程显示信息和关闭对话框
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                et_w6.setText(sbl);
                                //关闭对话框
                                dialog.dismiss();
                            }
                        });



                    }
                    else {
                        Toast.makeText(WebActivity.this, "连接错误,返回状态码=" + code, Toast.LENGTH_SHORT).show();
                    }


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

                    dialog.dismiss();
                }
            }

        }.start();
    }

    public void volleygetonclick(View view)
    {
        //1.进度对话框
        final ProgressDialog progressDialog = ProgressDialog.show(this,null,"正在加载,请稍后。。。");

        //构造Volley的请求对象 参数:1-地址 2-正常处理监听 3-错误处理监听
        StringRequest sr = new StringRequest(et_w5.getText().toString() + "?name=jack", new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {

                et_w6.setText(s);

                progressDialog.dismiss();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                Toast.makeText(WebActivity.this, "访问异常", Toast.LENGTH_SHORT).show();
                //出错也要关闭
                progressDialog.dismiss();

            }
        });

        //把请求对象放入队列
        requestQueue.add(sr);
    }

    public void volleypostonclick(View view)
    {
        //1.进度对话框
        final  ProgressDialog progressDialog = ProgressDialog.show(this,null,"正在加载,请稍后。。。");

        //构造Volley的请求对象
        StringRequest sr = new StringRequest(Request.Method.POST,et_w5.getText().toString(), new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {

                et_w6.setText(s);
                progressDialog.dismiss();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                Toast.makeText(WebActivity.this, "访问异常", Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
            }
        }){
            //重写设置参数的方法
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String,String> m = new HashMap<String,String>();
                m.put("name","volley");

                return m;
            }
        };
        //把请求对象放入队列

        requestQueue.add(sr);


    }
}

首先得获得权限:

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

activity_web.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.hanqi.test5.WebActivity"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_w5"
        android:hint="URL地址"
        android:text="http://192.168.0.122:8080/TestWeb/index.jsp"/>
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="JDK_Get方式"
        android:onClick="getonclick"/>
    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="JDK_Post方式"
        android:onClick="postonclick"/>
</LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Android的Get方式"
            android:onClick="bt7_OnClick"/>
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Android的Post方式"
            android:onClick="bt8_OnClick"/>
    </LinearLayout>

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Volley的Get方式"
    android:onClick="volleygetonclick"/>
<Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:text="Volley的Post方式"
    android:onClick="volleypostonclick"/>
</LinearLayout>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/et_w6"/>

</LinearLayout>

 

效果图:

 

posted @ 2016-04-22 08:46  秦萧不再  阅读(305)  评论(0编辑  收藏  举报