数据服务器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();
		}
		
	}
}

    
 

    
实现结果如下:

 

    数据和服务器数据和服务器

 

文章结束给大家分享下程序员的一些笑话语录: 古鸽是一种搜索隐禽,在中国快绝迹了…初步的研究表明,古鸽的离去,很可能导致另一种长着熊爪,酷似古鸽,却又习性不同的猛禽类——犤毒鸟

posted @ 2013-05-08 20:13  xinyuyuanm  阅读(324)  评论(0编辑  收藏  举报