android网络编程之——客户端上传信息到网络上面网页(POST)

     本文主要根据代码实例来分析安卓客户端上传文本信息到网络的网页。

1、业务类实现,包括3个参数

public class ServiceSubmit {

	public static boolean submitPost(String s1, String s2, String url) throws IOException{
		Map<String,String> params = new HashMap<String,String>() ;
		params.put("name", s1) ;
		params.put("age", s2) ;
		
		return sendPostQuest(url,params, "UTF-8") ;
		
	}
	
	private static boolean sendPostQuest(String url, Map<String, String> params,
			String encoding) throws IOException {
		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 conn = (HttpURLConnection) new URL(url).openConnection() ;
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("POST");
		conn.setDoOutput(true); //允许对外传输数据
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestProperty("Content-Length", data.length + "");
		
		OutputStream os = conn.getOutputStream() ;
		os.write(data);
		os.flush(); 
		
		if(conn.getResponseCode() == 200){
			return true ;
		}
		return false;
	}
	
	
}


2、GET servlet中的doPost内容,由于客户端的编码是ISO8859-1,所以此处进行了编码改变,这样控制台输出时就不会出现中文乱码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name = new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8") ;
		String age = request.getParameter("age") ;
		
		System.out.println("post method name is: " + name) ;
		System.out.println("post method pwd is: " + age) ;
		System.out.println("this is test. " ) ;
		response.getWriter().println(name); 
		response.getWriter().println(age); 
		//response.getOutputStream().println(age); ;
		//response.getOutputStream().println("测试中文"); ;

		//response.getOutputStream().println("OK") ;
	}

3、主页面实现

public void submitPostServer(String s1,String s2, String url) throws IOException{
		boolean result = false ;
		result = ServiceSubmit.submitPost(s1,s2, url) ;
		if(result){
			Toast.makeText(this, "this is ok,", 1).show(); 
		}else{
			Toast.makeText(this, "this is no ok,", 1).show(); 
		}

	}

String url_one = "http://172.27.251.31:8081/TestWeb/GetMethod" ;
				String s1 = et_submit_1.getText().toString() ;
				String s2 = et_submit_2.getText().toString() ;
				
				try {
					submitPostServer(s1, s2, url_one);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 


PS:如果需要定时进行上传数据,可以使用timer,具体的请参考另外关于timer的文章。



你可能感兴趣的:(android网络编程之——客户端上传信息到网络上面网页(POST))