android 原生GET和POST提交数据

package com.example.get;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                Toast.makeText(MainActivity.this, "服务器异常", 0).show();
            } else if (msg.what == 1) {
                Toast.makeText(MainActivity.this, msg.obj.toString(), 0).show();
            }
        };
    };

    private String password;
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void doLogin(View v) {
        EditText etName = (EditText) findViewById(R.id.et_name);
        EditText etPwd = (EditText) findViewById(R.id.et_password);

        name = etName.getText().toString();
        password = etPwd.getText().toString();

        fetch();
    }

    public void doLoginForPost(View v) {
        EditText etName = (EditText) findViewById(R.id.et_name);
        EditText etPwd = (EditText) findViewById(R.id.et_password);

        name = etName.getText().toString();
        password = etPwd.getText().toString();

        fetchPost();
    }

    public void fetch() {
        Thread t = new Thread() {
            @Override
            public void run() {
                super.run();

                String path = "http://192.168.1.105:8080/android/AndroidServlet?username="
                        + URLEncoder.encode(name)
                        + "&password="
                        + URLEncoder.encode(password);

                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestMethod("GET");
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);

                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        byte[] b = new byte[1024];
                        int len = 0;
                        // 创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = is.read(b)) != -1) {
                            bos.write(b, 0, len);
                        }
                        // 把字节数组输出流的数据转换成字节数组
                        String text = new String(bos.toByteArray(), "utf-8");
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = text;
                        handler.sendMessage(msg);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    public void fetchPost() {
        Thread t = new Thread() {
            @Override
            public void run() {
                super.run();

                String path = "http://192.168.1.105:8080/android/AndroidServlet";

                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestMethod("POST");
                    conn.setReadTimeout(5000);
                    conn.setConnectTimeout(5000);

                    String params = "username=" + URLEncoder.encode(name)
                            + "&password=" + URLEncoder.encode(password);
                    conn.setRequestProperty("Content-Type",
                            "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", params.length()
                            + "");

                    // 设置打开输出流
                    conn.setDoOutput(true);
                    // 拿到输出流
                    OutputStream os = conn.getOutputStream();
                    os.write(params.getBytes());
                    os.flush();
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        byte[] b = new byte[1024];
                        int len = 0;
                        // 创建字节数组输出流,读取输入流的文本数据时,同步把数据写入数组输出流
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        while ((len = is.read(b)) != -1) {
                            bos.write(b, 0, len);
                        }
                        // 把字节数组输出流的数据转换成字节数组
                        String text = new String(bos.toByteArray(), "utf-8");
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = text;
                        handler.sendMessage(msg);
                    } else {
                        handler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
}

推荐阅读更多精彩内容