Android 提交数据到服务器

前几篇博客都是说怎么从服务器里拿数据,今天就讲讲怎么提交数据到服务器上。大致有两种方式,一种是底层做法,GETPOST方法;还有一种是第三方asynchttpclient框架

<?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"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_main_uname"
        android:hint="请输入用户名:"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_main_upass"
        android:hint="请输入密码:"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录(GET)"
        android:onClick="loginGET"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录(POST)"
        android:onClick="loginPOST"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录(AsyncHttpClient)"
        android:onClick="loginAsyncHttpClient"
        />

</LinearLayout>

一、底层做法:
1、get方法和post方法

public void loginGET(View view){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();
        new MyTask().execute(uname,upass,"GET");
    }
    public void loginPOST(View view){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();
        new MyTask().execute(uname,upass,"POST");
    }

因为这是一个耗时操作,所以必须写在子线程内:

class MyTask extends AsyncTask{

        private URL url;
        private HttpURLConnection connection;

        @Override
        protected Object doInBackground(Object[] objects) {

            String uname=objects[0].toString();
            String upass=objects[1].toString();
            String type=objects[2].toString();
            try {

                if("GET".equals(type)){
                    //用GET方式请求
                    url = new URL("http://193.168.3.134:8080/datatoclient/loginActionlogin.action?uname="+uname+"&upass="+upass);
                    Log.i("test","get方式");
                }else if("POST".equals(type)){
                    Log.i("test","post方式");
                    //用POST方式请求
                    url = new URL("http://193.168.3.134:8080/datatoclient/loginActionlogin.action");
                }
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod(type);
                connection.setConnectTimeout(5000);


                if("POST".equals(type)){
                    //设置可以允许对外输出数据
                    connection.setDoOutput(true);

                    String str="uname="+uname+"&upass="+upass;

                    //添加请求头
                    //Content-Length:24
                    connection.setRequestProperty("Content-Length",""+str.length());
                    //Content-Type:application/x-www-form-urlencoded
                    connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

                    //将内容提交到服务器
                    connection.getOutputStream().write(str.getBytes());
                }


                if(connection.getResponseCode()==200){
                    InputStream is= connection.getInputStream();
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String str=br.readLine();
                    return str;
                    //
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }


            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        //更新UI
        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

            String s= (String) o;
            if("success".equals(s.trim())){
                Toast.makeText(MainActivity.this, "跳转到主界面", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(MainActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }
            //创建时间  修改时间
        }
}

get和post方法都可以提交数据到服务器,那么到底它们有什么区别呢?
a、get方式提交,参数直接带入路径中
b、post不用带入路径,而且有两个特殊的属性:

//添加请求头
                    //Content-Length:24
                    connection.setRequestProperty("Content-Length",""+str.length());
                    //Content-Type:application/x-www-form-urlencoded
                    connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

c、而且还要设置可以允许对外输出数据:connection.setDoOutput(true);
二、第三方asynchttpclient

public void loginAsyncHttpClient(View view){
        String uname=et_main_uname.getText().toString();
        String upass=et_main_upass.getText().toString();

        AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
        RequestParams params=new RequestParams();
        params.put("uname",uname);
        params.put("upass",upass);
//        Ctrl+H
//        ResponseHandlerInterface
        asyncHttpClient.post("http://193.168.3.134:8080/G150725_S2SH/loginActionlogin.action",params,new TextHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, org.apache.http.Header[] headers, String responseBody) {
                super.onSuccess(statusCode, headers, responseBody);
                Toast.makeText(MainActivity.this, ""+responseBody, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int statusCode, org.apache.http.Header[] headers, String responseBody, Throwable error) {
                super.onFailure(statusCode, headers, responseBody, error);
            }
        });

    }
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android提供了多种数据存储形式,包括文件系统、SQLite数据库、Shared Preferences、网络存储和Content Provider。下面是对每种数据存储形式的简要介绍: 1. 文件系统:Android允许应用程序在内部存储和外部存储上创建和访问文件。内部存储是应用程序有的,只被应用程序本身访问。外存储可以被应用程序和用户访问。文件系统适用于存储较大的数据文件,如图片、音频视频等。 2. SQLite数据库:SQLite是一种轻量级的关系型数据库,Android提供了SQLite数据库的支持。开发者可以使用SQLite数据库来存储管理结构化数据。SQLite数据库适用于存储和查询大量结构化数据,如用户信息、日志和配置等。 3. Shared Preferences:Shared Preferences是一种轻量级的键值对存储方式,用于存储应用程序的配置信息和用户偏好设置。Shared Preferences适用于存储少量简单的数据,如用户设置、应用程序状态和计数器等。 4. 网络存储:Android应用程序可以通过网络连接来访问和存储数据。开发者可以使用HTTP协议与服务器进行通信,通过GET和POST请求来获取和提交数据。网络存储适用于需要与服务器进行数据交互的应用程序,如社交媒体应用和在线购物应用等。 5. Content Provider:Content Provider是Android提供的一种跨应用程序共享数据的机制。开发者可以使用Content Provider来存储和共享结构化数据,其他应用程序可以通过Content Resolver来访问和操作这些数据。Content Provider适用于需要共享数据给其他应用程序使用的应用程序,如联系人、日历和媒体库等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值