【Android】安卓开发之使用Gson和POST请求和服务器通信

来源:互联网 发布:人工智能假肢多少钱 编辑:程序博客网 时间:2024/05/18 10:52

一、先看接口文档

url:http://10.15.120.43:8080/APP/Register(假设是这个地址,实际并不是)

请求方式:Http-Post

Content-Type: application/json

请求参数

{ “username”:”用户名”,“password”:”登录密码”}

返回参数

{“code”:”响应状态码”,“msg”: “响应信息”}

二、添加依赖

1、在Android studio 的project的Android视图下,打开build.gradle(Module:app)文件,添加依语句compile 'com.google.code.gson:gson:2.7'

dependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {        exclude group: 'com.android.support', module: 'support-annotations'    })    compile 'com.android.support:appcompat-v7:25.1.0'    testCompile 'junit:junit:4.12'    compile 'com.google.code.gson:gson:2.7'}
2、点击右上角的 Sync now同步文本,然后Android studio 会自动下载Gson2.7,等它下载完就好了。

三、打开网络请求

打开manifests文件夹下的AndroidManifest.xml文件,加上<uses-permission android:name="android.permission.INTERNET"/>

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.test">    <uses-permission android:name="android.permission.INTERNET"/>    <application
四、在Java文件夹下新建一个Bean包,包下新建一个CalBean类,CalBean类里的代码如下:
package Bean;public class CalBean {    private String username;    private String password;    public CalBean(String username,String password) {        this.username = username;        this.password = password;    }    public String getUsername() {        return username;    }    public void setUsername(String username) {        this.username = username;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    @Override    public String toString() {        return "CalBean{" + "username=" + username + ", password=" + password +"}";    }}
五、在注册页的Activity类进行相应设置

/** * 注册页面2活动 */public class RegisterPart2 extends BaseActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.new_register_part2);        //---------------------------给状态栏设置颜色-----------------------------------------------        TextView textViewActionBar = (TextView) findViewById(R.id.actionBarId);        setActionBarColor(textViewActionBar, getResources().getColor(R.color.theRed));        //------------------------------------------------------------------------------------------        final EditText regUserName = (EditText) findViewById(R.id.regist2NameEditId);        final EditText regPassword = (EditText) findViewById(R.id.regist2PasswordEditId);        EditText regConfirm = (EditText) findViewById(R.id.regist2ConfirmEditId);        EditText regEmail = (EditText) findViewById(R.id.regist2EmailEditId);        Button confirmButton = (Button) findViewById(R.id.regist2ConfirmBottonId);        /**         * 完成注册,销毁之前的注册活动,直接跳到登陆界面,且不可返回之前注册活动         */        confirmButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                //---------------------------获取输入的用户名和密码---------------------------------                String name = regUserName.getText().toString();                String password = regPassword.getText().toString();                //----------------------------------------------------------------------------------                //---------------------通过POST请求将用户名和密码发送给服务器-----------------------                try {                    //新建一个线程,通过Message消息通知Handle对UI进行更改,现在只能在UI线程里对UI组件进行更改。                    new Thread(new Runnable() {                        @Override                        public void run() {                            //下面三句话,将会把三个参数包装为{"para1":10,"para2":2,"opt":"div"}字段                            CalBean tb = new CalBean("12345678902","123456");                            Gson gson = new Gson();                            //传入的参数                            String datas = gson.toJson(tb);                            String url = " http://10.1.19.43:8080/Register";                            String data = sendPostRequest(url, datas);                        }                    }).start();                } catch (Exception e) {                    Log.i("ok", "there must be something wrong!");                    return;                }                //----------------------------------------------------------------------------------                Intent intent = new Intent(RegisterPart2.this, Login.class);                startActivity(intent);                ActivityCollector.finishAll();            }        });    }    public static String sendPostRequest(String url, String param) {        HttpURLConnection httpURLConnection = null;        OutputStream out = null; //写        InputStream in = null;   //读        int responseCode = 0;    //远程主机响应的HTTP状态码        String result = "";        try {            URL sendUrl = new URL(url);            httpURLConnection = (HttpURLConnection) sendUrl.openConnection();            //post方式请求            httpURLConnection.setRequestMethod("POST");            //设置头部信息            httpURLConnection.setRequestProperty("headerdata", "ceshiyongde");            //一定要设置 Content-Type 要不然服务端接收不到参数            httpURLConnection.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");            //指示应用程序要将数据写入URL连接,其值默认为false(是否传参)            httpURLConnection.setDoOutput(true);            //httpURLConnection.setDoInput(true);            httpURLConnection.setUseCaches(false);            httpURLConnection.setConnectTimeout(30000); //30秒连接超时            httpURLConnection.setReadTimeout(30000);    //30秒读取超时            //传入参数            out = httpURLConnection.getOutputStream();            out.write(param.getBytes());            out.flush(); //清空缓冲区,发送数据            out.close();            responseCode = httpURLConnection.getResponseCode();            //获取请求的资源            BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));            result = br.readLine();        } catch (Exception e) {            e.printStackTrace();        }        Map<String, String> map = new Gson().fromJson(result, new TypeToken<Map<String, String>>(){}.getType());        String msg = map.get("msg");        return msg;    }}



最后设一个断点看一下效果:



0 0
原创粉丝点击