Android-向服务器提交数据(GET-POST-AsyncHttpClient)





    
    
    

在Activity里面提交数据,在点击事件里面,我们只能获取输入框的值,而其他的操作我们就需要写到子线程中去,POST提交数据,点击事件和GET的一样,只是在参数的地方,我们需要多添加一个类型,为了区分在doInBackground方法里面,我们需要先判断是哪种类型的提交方式,然后把POST方法里多出来的那两个头部内容添加进去,再把内容提交服务器,就可以了,还有一种第三方网络请求框架AsyncHttpClient我们先把android-async-http-1.4.4.jar下到本地,然后拷到项目里,因为HttpClient有导致一些小问题,所以我们需要在Gradle的版本前添加一句useLibrary 'org.apache.http.legacy'在点击事件里面写提交数据,在httpClient.post方法里面,带来地址,和参数,还有一个Handler,然后重写Handler的两个方法即可。

package com.zking.administrator.g160628_android32_commitdata;

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

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private EditText et_main_uname;
    private EditText et_main_upass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_main_uname = (EditText) findViewById(R.id.et_main_uname);
        et_main_upass = (EditText) findViewById(R.id.et_main_upass);
    }
    //get方法
    public void loginGet(View view){
       //账号
        String uname=et_main_uname.getText().toString();
        //密码
        String upass=et_main_upass.getText().toString();
        //路径(Android端要调用.do/servlet)
        String path="http://193.168.3.70:8080/Web_server/login.do";
        new MyGetTask().execute(uname,upass,path);//execute中的object是一个可变数组
    }
    /**
     * 一般我们都不支持用get提交
     */
    class MyGetTask extends AsyncTask{

        @Override
        protected Object doInBackground(Object[] params) {
            String uname=params[0].toString();
            String upass=params[1].toString();
            String path=params[2].toString();
            //把账号密码提交到服务器
            try {
                URL url=new URL(path+"?uname="+uname+"&upass="+upass);
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                //设置请求方式
                connection.setRequestMethod("Get");
                //超时
                connection.setConnectTimeout(5000);
                //判断结果码
                if(connection.getResponseCode()==200){
                    InputStream is=connection.getInputStream();
                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                    String s=br.readLine();
                    return s;
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String s= (String) o;
            Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
        }

        //post方法
        public void loginPost(View view){
            //账号
            String uname=et_main_uname.getText().toString();
            //密码
            String upass=et_main_upass.getText().toString();
            //路径(Android端要调用.do/servlet)
            String path="http://193.168.3.70:8080/Web_server/login.do";
            new MyPostTask().execute(uname,upass,path);//execute中的object是一个可变数组
        }

        class MyPostTask extends AsyncTask{

            @Override
            protected Object doInBackground(Object[] params) {
                String uname=params[0].toString();
                String upass=params[1].toString();
                String path=params[2].toString();
                //把账号密码提交到服务器
                try {
                    URL url=new URL(path);
                    HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                    //设置请求方式
                    connection.setRequestMethod("POST");
                    //超时时间
                    connection.setConnectTimeout(5000);
                    //字符串拼接
                    String s="uname="+uname+"&upass="+upass;
                    //添加请求头(做Java程序要知道如何给Android程序员去写接口文档)
                    connection.setRequestProperty("Content-Length",s.length()+"");
                    connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                    connection.setDoOutput(true);//允许对外输出数据
                    OutputStream os=connection.getOutputStream();//写
                    os.write(s.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 onPostExecute(Object o) {
                super.onPostExecute(o);
                String str= (String) o;
                Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
            }
        }

        //AsyncHttpClient第三方
        public void loginAsyncHttpClient(View view){
            String uname=et_main_uname.getText().toString();
            String upass=et_main_upass.getText().toString();
            String path="http://193.168.3.70:8080/Web_server/login.do";

            AsyncHttpClient ahc=new AsyncHttpClient();
            RequestParams params=new RequestParams();
            params.put("uname",uname);
            params.put("upass",upass);
            ahc.post(MainActivity.this,path,params,new TextHttpResponseHandler(){
                @Override
                public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) {
                    super.onFailure(statusCode, headers, responseBody, error);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, String responseBody) {
                    super.onSuccess(statusCode, headers, responseBody);
                    Toast.makeText(MainActivity.this, responseBody, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}




你可能感兴趣的:(Android)