采用Post方式提交数据实例

项目目录

一、编写MainActivity.java

package com.hyzhou.getdemo;

import com.hyzhou.getdemo.service.LoginServer;

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

public class MainActivity extends Activity {

    private EditText et_username, et_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
    }

    public void click(View view) {
        final String username = et_username.getText().toString().trim();
        final String password = et_password.getText().toString().trim();
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                final String result = LoginServer
                        .loginByPost(username, password);
                if (result != null) {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            Toast.makeText(MainActivity.this, result, 0).show();
                        }
                    });
                } else {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            Toast.makeText(MainActivity.this, "请求失败", 0).show();
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}
View Code

二、编写LoginServer.java

/**
 * 
 */
package com.hyzhou.getdemo.service;

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

import com.hyzhou.getdemo.utiils.StreamTools;

/**
 * @author hyzhou
 *
 * 2013-11-6
 */
public class LoginServer {
    public static String loginByPost(String username,String password)
    {
        
        try {
            String path="http://192.168.1.54:8080/web/LoginServlet";
            URL url=new URL(path);
            HttpURLConnection conn=(HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("POST");
            //准备数据
            String data="username="+username+"&password="+password;
            conn.setRequestProperty("content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", data.length()+"");
            //post 的方式实际上是浏览器把数据写给服务器
            conn.setDoOutput(true);
            OutputStream os=conn.getOutputStream();
            os.write(data.getBytes());
            
            int code=conn.getResponseCode();
            if (code==200) {
                InputStream is=conn.getInputStream();
                String text=StreamTools.readInputStream(is);
                return text;
            }else {
                return null;
            }
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
View Code

三、编写StreamTools.java

/**
 * 
 */
package com.hyzhou.getdemo.utiils;

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


/**
 * @author hyzhou
 *
 * 2013-11-6
 */
public class StreamTools {

    /**
     * 把输入流内容转化成字符串
     */
    public static String readInputStream(InputStream is) {        
        try {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            int len=0;
            byte[] buffer=new byte[1024];
            while ((len=is.read(buffer))!=-1) {
                baos.write(buffer,0,len);
            /**
 * 
 */
package com.hyzhou.getdemo.utiils;

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


/**
 * @author hyzhou
 *
 * 2013-11-6
 */
public class StreamTools {

    /**
     * 把输入流内容转化成字符串
     */
    public static String readInputStream(InputStream is) {        
        try {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            int len=0;
            byte[] buffer=new byte[1024];
            while ((len=is.read(buffer))!=-1) {
                baos.write(buffer,0,len);
            }
            is.close();
            baos.close();
            byte[] result=baos.toByteArray();
            //试着解析result中的字符串
            String temp=new String(result);
            return temp;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return "获取失败";
        }
        
    }
}
/**
 * 
 */
package com.hyzhou.getdemo.utiils;

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


/**
 * @author hyzhou
 *
 * 2013-11-6
 */
public class StreamTools {

    /**
     * 把输入流内容转化成字符串
     */
    public static String readInputStream(InputStream is) {        
        try {
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            int len=0;
            byte[] buffer=new byte[1024];
            while ((len=is.read(buffer))!=-1) {
                baos.write(buffer,0,len);
            }
            is.close();
            baos.close();
            byte[] result=baos.toByteArray();
            //试着解析result中的字符串
            String temp=new String(result);
            return temp;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return "获取失败";
        }
        
    }
}
View Code

 PS:相对get请求,Post请求相对复杂,需要指定Content-Type、Content-Length等

原文地址:https://www.cnblogs.com/hyzhou/p/3410932.html