码迷,mamicode.com
首页 > 移动开发 > 详细

Android开发使用POST方式向服务器请求和发送数据

时间:2014-07-29 14:49:49      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:android   安卓   移动开发   post   网络   

前面说了GET方式。现在尝试一下POST


#1.首先先用新建个servlet处理登陆请求


package com.wzw.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		if(username.equals("admin")&&password.equals("123456")){
			response.getWriter().println("success");
		}else{
			response.getWriter().println("failed");
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
<span style="white-space:pre">		</span>this.doGet(request,response);
	}

}

#2.布局文件也很简单

<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=".MainActivity" >

    <EditText
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_username"
        android:hint="请输入名字"/>
    <EditText
        android:layout_marginTop="10dp"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/et_password"
        android:hint="请输入密码"/>
    
    <Button android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	    android:onClick="doGet"
	    android:text="GET方式提交"/>
    
	<Button android:layout_height="wrap_content"
	    android:layout_width="wrap_content"
	      android:onClick="doPost"
	    android:text="POST方式提交"/>
</LinearLayout>

#3在mainactivity中实现方法

package com.wzw.submitdata;

import com.wzw.submitdata.utils.NetUtil;

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 etUsername;
	private EditText etPassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		etUsername = (EditText) findViewById(R.id.et_username);
		etPassword = (EditText) findViewById(R.id.et_password);
		
		
		
	}
	public void doGet(View v){
		final String username=etUsername.getText().toString();
		final String password=etPassword.getText().toString();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				//访问网络要在子线程中实现,使用get取数据
				final String state=NetUtil.loginOfGet(username, password);
				
				//执行在主线程上
				runOnUiThread(new Runnable() {
					public void run() {
						//就是在主线程上操作,弹出结果
						Toast.makeText(MainActivity.this, state, 0).show();
						
					}
				});
			}
		}).start();
		
	}

	public void doPost(View v){
		final String username=etUsername.getText().toString();
		final String password=etPassword.getText().toString();
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				final String state=NetUtil.LoginOfPost(username, password);
				//执行在主线程上
				runOnUiThread(new Runnable() {
					public void run() {
						//就是在主线程上操作,弹出结果
						Toast.makeText(MainActivity.this, state, 0).show();
						
					}
				});
				
			}
			
		}).start();
		
		
	}

	
	
	
}


#4.具体处理GET和POST的方法

package com.wzw.submitdata.utils;

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

public class NetUtil {


	/**
	 * 使用GET访问去访问网络
	 * @param username
	 * @param password
	 * @return 服务器返回的结果
	 */
	public static String loginOfGet(String username,String password){
		HttpURLConnection conn=null;
		try {
			String data="username="+username+"&password="+password;
			URL url=new URL("http://192.168.1.4:8080/AndroidServer/LoginServlet?"+data);
			conn=(HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(5000);
			conn.connect();
			int code=conn.getResponseCode();
			if(code==200){
				InputStream is=conn.getInputStream();
				String state=getStringFromInputStream(is);
				return state;
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(conn!=null){
				conn.disconnect();
			}
		}
		
		
		return null;
	}
	

	/**
	 * 使用POST访问去访问网络
	 * @param username
	 * @param password
	 * @return
	 */
	public static String LoginOfPost(String username,String password){
		HttpURLConnection conn=null;
		try {
			URL url=new URL("http://192.168.1.4:8080/AndroidServer/LoginServlet");
			conn=(HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(5000);
			conn.setDoOutput(true);
			//post请求的参数
			String data="username="+username+"&password="+password;
			OutputStream out=conn.getOutputStream();
			out.write(data.getBytes());
			out.flush();
			out.close();
			
			
			conn.connect();
			int code=conn.getResponseCode();
			if(code==200){
				InputStream is=conn.getInputStream();
				String state=getStringFromInputStream(is);
				return state;
			}
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(conn!=null){
				conn.disconnect();
			}
		}
		
		
		
		return null;
	}
	
	
	
	/**
	 * 根据输入流返回一个字符串
	 * @param is
	 * @return
	 * @throws Exception 
	 */
	private static String getStringFromInputStream(InputStream is) throws Exception{
	
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		byte[] buff=new byte[1024];
		int len=-1;
		while((len=is.read(buff))!=-1){
			baos.write(buff, 0, len);
		}
		is.close();
		String html=baos.toString();
		baos.close();
		
		
		return html;
	}
}




Android开发使用POST方式向服务器请求和发送数据,布布扣,bubuko.com

Android开发使用POST方式向服务器请求和发送数据

标签:android   安卓   移动开发   post   网络   

原文地址:http://blog.csdn.net/ibey0nd/article/details/38234839

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!