android中用GET和POST的方法向服务器上传数据

                    GET和POST都能实现向服务器中上传数据,

GET向服务器上传数据工程源码下载地址:客户端:   源码下载   服务器端:源码下载

POST向服务器上传数据工程源码下载地址:客户端:  源码下载     服务器端:源码下载

 

两者的区别如下:

GET上传的数据一般是很小的并且安全性能不高的数据, 而POST上传的数据适用于数据量大,数据类型复杂,数据安全性能要求高的地方

GET和POST的使用方法一般如下:

1.采用GET方式向服务器传递数据的步骤


1.利用Map集合对数据进行获取并进行数据处理
if (params!=null&&!params.isEmpty()) {
 for (Map.Entry<String, String> entry:params.entrySet()) {
    
  sb.append(entry.getKey()).append("=");
  sb.append(URLEncoder.encode(entry.getValue(),encoding));
  sb.append("&");
   }
  sb.deleteCharAt(sb.length()-1);
   
  }
 
2.新建一个StringBuilder对象
  sb=new StringBuilder()
3.新建一个HttpURLConnection的URL对象,打开连接并传递服务器的path
connection=(HttpURLConnection) new URL(path).openConnection();
4.设置超时和连接的方式

 connection.setConnectTimeout(5000);
  connection.setRequestMethod("GET");

2.采用POST方式向服务器传递数据的步骤

 

1.利用Map集合对数据进行获取并进行数据处理
if (params!=null&&!params.isEmpty()) {
 for (Map.Entry<String, String> entry:params.entrySet()) {
    
  sb.append(entry.getKey()).append("=");
  sb.append(URLEncoder.encode(entry.getValue(),encoding));
  sb.append("&");
   }
  sb.deleteCharAt(sb.length()-1);
   
  }
 
2.新建一个StringBuilder对象,得到POST传给服务器的数据
  sb=new StringBuilder()
  byte[] data=sb.toString().getBytes();
3.新建一个HttpURLConnection的URL对象,打开连接并传递服务器的path
connection=(HttpURLConnection) new URL(path).openConnection();
4.设置超时和允许对外连接数据
connection.setDoOutput(true);
5.设置连接的setRequestProperty属性

connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  connection.setRequestProperty("Content-Length", data.length+"");
6.得到连接输出流
outputStream =connection.getOutputStream();
7.把得到的数据写入输出流中并刷新
 outputStream.write(data);
 outputStream.flush();

 

3.具体实现的过程如下:

1.使用GET方法上传数据

服务器中doGet方法中的代码如下:

 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String name =request.getParameter("name");
		String age=request.getParameter("age");
		System.out.println("--------name:"+name);
		System.out.println("--------age:"+age);
		
	}


在客户端实现的代码如下:

 

public class UserSerivce {

	public static boolean save(String getname, String getage) throws Exception {

		String path = "http://10.254.1.62/WebForGETMethod/ServletForGetMethod";

		Map<String, String> params = new HashMap<String, String>();
		params.put("name", getname);
		params.put("age", getage);

		return sendGETRequest(path, params, "UTF-8");
	}

	private static boolean sendGETRequest(String path,
			Map<String, String> params, String encoding) throws Exception {

		StringBuilder sb = new StringBuilder(path);
		if (params != null && !params.isEmpty()) {
			sb.append("?");
			for (Map.Entry<String, String> entry : params.entrySet()) {

				sb.append(entry.getKey()).append("=");
				sb.append(URLEncoder.encode(entry.getValue(), encoding));
				sb.append("&");
			}
			sb.deleteCharAt(sb.length() - 1);
		}

		HttpURLConnection connection = (HttpURLConnection) new URL(
				sb.toString()).openConnection();
		connection.setConnectTimeout(5000);
		connection.setRequestMethod("GET");
		if (connection.getResponseCode() == 200) {
			return true;
		}

		return false;
	}

}


然后呢,就是实现在android客户端的界面

 

public class GetDataToWebActivity extends Activity {
private EditText name,age;
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.getdate);
        name=(EditText) findViewById(R.id.name);
        age=(EditText) findViewById(R.id.age);
    }
	public void save(View v) {
		String getname=name.getText().toString();
		String getage=age.getText().toString();
		
		boolean result=false;
		try {
			result=UserSerivce.save(getname,getage);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (result) {
			Toast.makeText(this, "成功", 1).show();
			
		}else {
			Toast.makeText(this, "失败", 1).show();
		}	
	}
}


实现结果如下:

 

 

 

2.使用POST方法上传数据

在服务器实现的代码如下:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		String name=request.getParameter("name");
		String age=request.getParameter("age");
		System.out.println("name form post method "+name);
		System.out.println("age from post method"+age);
		
	}

在客户端实现的代码如下:

public class postService {

	public static boolean save(String name, String age) throws Exception {

	String path="http://10.254.1.62/WebForPOSTMethod/POSTMethodServlet";
		
	Map<String, String> params=new HashMap<String, String>();
	params.put("name", name);
	params.put("age", age);
		return SendPOSTRequest(path,params,"UTF-8");
	}

	private static boolean SendPOSTRequest(String path,
			Map<String, String> params, String encoding) throws Exception {
 
		StringBuilder sb=new StringBuilder();
		if (params!=null&&!params.isEmpty()) {
			for (Map.Entry<String, String> entry:params.entrySet()) {
				
				sb.append(entry.getKey()).append("=");
				sb.append(URLEncoder.encode(entry.getValue(),encoding));
				sb.append("&");
			}
			sb.deleteCharAt(sb.length()-1);
			
		}
    
		byte[] data=sb.toString().getBytes();
		HttpURLConnection connection=(HttpURLConnection) new URL(path).openConnection();
		connection.setConnectTimeout(5000);
		//允许对外连接数据
		connection.setDoOutput(true);
		
		connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		connection.setRequestProperty("Content-Length", data.length+"");
		OutputStream outputStream =connection.getOutputStream();
		outputStream.write(data);
		outputStream.flush();
		if (connection.getResponseCode()==200) {
			return true;
		}
		return false;
	}

}



 

然后呢,就是实现在android客户端的界面

public class POSTDateToWebActivity extends Activity {
 
	EditText getname,getage;
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post);
        getname=(EditText) findViewById(R.id.name);
       getage=(EditText) findViewById(R.id.age);
    }
	public void save(View v){
		boolean result=false;
		String name=getname.getText().toString();
		String age=getage.getText().toString();
		try {
			result=postService.save(name,age);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if (result) {
			Toast.makeText(this, "success",1).show();
		}else {
			Toast.makeText(this, "error",1).show();
		}
		
	}
}


 


实现结果如下:

 

 

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员Android

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值