Android 提交数据到服务器

来源:互联网 发布:安卓鼓机软件loopz 编辑:程序博客网 时间:2024/05/01 01:31

前几篇博客都是说怎么从服务器里拿数据,今天就讲讲怎么提交数据到服务器上。大致有两种方式,一种是底层做法,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);            }        });    }
0 0