Android之POST方法的使用

java代码


 

package xidian.dy.com.chujia;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    String username;
    String password;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Toast.makeText(MainActivity.this,(String)msg.obj, Toast.LENGTH_SHORT).show();
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        Button submit = (Button) findViewById(R.id.submit);
        if(submit != null)
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText etuser = (EditText) findViewById(R.id.username);
                EditText etpass = (EditText) findViewById(R.id.password);
                if(etpass !=null && etuser != null){
                    username = etuser.getText().toString();
                    password = etpass.getText().toString();
                    Log.i("login_username", username);
                    Log.i("login_password", password);
                }
                login();
            }
        });

    }
    private void login(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://192.168.0.162/test.php");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);
                    StringBuilder sb = new StringBuilder();
                    sb.append("username=").append(username).append("&password=").append(password);
                    conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", sb.length()+"");
                    //打开输入流
                    conn.setDoOutput(true);
                    //建立连接
                    //建连接和打开流的顺序不能乱
                    conn.connect();
                    OutputStream os = conn.getOutputStream();
                    os.write(sb.toString().getBytes());
                    //获取服务器应答数据
                    if(conn.getResponseCode() == 200){
                       InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = handler.obtainMessage();
                        msg.obj = text;
                        handler.sendMessage(msg);
                        is.close();
                    }
                    os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}

布局文件


<?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:orientation="vertical"
    tools:context="xidian.dy.com.chujia.MainActivity">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/usr"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="22sp"
                    android:text="用户名"/>
                <EditText
                    android:id="@+id/username"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/usr"/>
        </RelativeLayout>
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
                <TextView
                    android:id="@+id/p"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="22sp"
                    android:text="密码"/>
                <EditText
                    android:id="@+id/password"
                    android:inputType="textPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/p"/>
        </RelativeLayout>
        <Button
            android:id="@+id/submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="提交"/>

</LinearLayout>

工具类


package xidian.dy.com.chujia;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by dy on 2016/6/28.
 */
public class Utils {

    public static String getTextFromStream(InputStream is){

        byte[] b = new byte[1024];
        int len = 0;
        //创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while((len = is.read(b)) != -1){
                bos.write(b, 0, len);
            }
            //把字节数组输出流里的数据转换成字节数组
            String text = new String(bos.toByteArray());
            return text;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

 

 

posted @ 2016-06-28 23:12  被罚站的树  阅读(1328)  评论(0编辑  收藏  举报