Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android網絡編程之傳遞數據給服務器(一)

Android網絡編程之傳遞數據給服務器(一)

編輯:關於Android編程

Android網絡編程之傳遞數據給服務器(一)

請尊重他人的勞動成果,轉載請注明出處:Android網絡編程之傳遞數據給服務器(一)


因為Android程序需要和服務器進行通信,所以需要服務器端提供的支持。

一、通過GET方式傳遞數據給服務器

通過GET方式上傳數據主要適用於數據大小不超過2KB,且對安全性要求不高的情況下。

1.創建服務器端:

服務器端項目結構:

通過GET方式傳遞數據給服務器——服務器端項目結構

第一步:創建控制器Servlet

package com.jph.sgm.servlet;

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

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

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//獲取請求的參數(使用utf-8進行解碼,然後用進行ISO8859-1編碼)
//		String name=new String(request.getParameter("name").getBytes("ISO8859-1"),"utf-8");		
		String name=request.getParameter("name");		
		String pwd=request.getParameter("pwd");
		System.out.println("name:"+name+"   pwd:"+pwd);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

第二步:測試Servlet

發布項目並在浏覽器中輸入:http://localhost:8080/ServerForGETMethod/ServletForGETMethod?name=aa&pwd=124

可以再控制台看到如下圖的輸出:


通過GET方式傳遞數據給服務器——服務器端測試結果

至此服務器端項目已經完成。下面開始創建Android端項目。

2.創建Android端:

Android端項目結構:

通過GET方式傳遞數據給服務器——Android端項目結構


第一步:創建Android端項目的業務邏輯層

核心代碼:SendDateToServer.java:

package com.jph.sdg.service;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import android.os.Handler;

/**
 * 通過GET方式向服務器發送數據
 * @author jph
 * Date:2014.09.27
 */
public class SendDateToServer {
	private static String url="http://10.219.61.117:8080/ServerForGETMethod/ServletForGETMethod";
	public static final int SEND_SUCCESS=0x123;
	public static final int SEND_FAIL=0x124;
	private Handler handler;
	public SendDateToServer(Handler handler) {
		// TODO Auto-generated constructor stub
		this.handler=handler;
	}	
	/**
	 * 通過Get方式向服務器發送數據
	 * @param name 用戶名
	 * @param pwd  密碼
	 */
	public void SendDataToServer(String name,String pwd) {
		// TODO Auto-generated method stub
		final Mapmap=new HashMap();
		map.put("name", name);
		map.put("pwd", pwd);
		new Thread(new Runnable() {			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					 if (sendGetRequest(map,url,"utf-8")) {
						handler.sendEmptyMessage(SEND_SUCCESS);//通知主線程數據發送成功
					}else {
						//將數據發送給服務器失敗
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}				
			}
		}).start();
	}
	/**
	 * 發送GET請求
	 * @param map 請求參數
	 * @param url 請求路徑
	 * @return
	 * @throws Exception 
	 */
	private  boolean sendGetRequest(Map param, String url,String encoding) throws Exception {
		// TODO Auto-generated method stub
		//http://localhost:8080/ServerForGETMethod/ServletForGETMethod?name=aa&pwd=124
		StringBuffer sb=new StringBuffer(url);
		if (!url.equals("")&!param.isEmpty()) {
			sb.append("?");
			for (Map.Entryentry:param.entrySet()) {
				sb.append(entry.getKey()+"=");				
					sb.append(URLEncoder.encode(entry.getValue(), encoding));				
				sb.append("&");
			}
			sb.deleteCharAt(sb.length()-1);//刪除字符串最後 一個字符“&”
		}
		HttpURLConnection conn=(HttpURLConnection) new URL(sb.toString()).openConnection();
		conn.setConnectTimeout(5000);
		conn.setRequestMethod("GET");//設置請求方式為GET
		if (conn.getResponseCode()==200) {
			return true;
		}
		return false;
	}

}

第三步:創建Activity

package com.jph.sdg.activity;

import com.jph.sdg.R;
import com.jph.sdg.service.SendDateToServer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/**
 * 通過GET方式向服務器發送數據,通過GET方式上傳數據主要適用於數
 * 據大小不超過2KB,且對安全性要求不高的情況下。
 * @author jph
 * Date:2014.09.27
 */
public class MainActivity extends Activity {
	private EditText edtName,edtPwd;
	private Button btnSend;
	Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SendDateToServer.SEND_SUCCESS:
				Toast.makeText(MainActivity.this, "登陸成功", Toast.LENGTH_SHORT).show();
				break;
			case SendDateToServer.SEND_FAIL:
				Toast.makeText(MainActivity.this, "登陸失敗", Toast.LENGTH_SHORT).show();
				break;

			default:
				break;
			}
		};		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edtName=(EditText)findViewById(R.id.edtName);
		edtPwd=(EditText)findViewById(R.id.edtPwd);
		btnSend=(Button)findViewById(R.id.btnSend);
		btnSend.setOnClickListener(new OnClickListener() {			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String name=edtName.getText().toString();
				String pwd=edtPwd.getText().toString();
				if (edtName.equals("")||edtPwd.equals("")) {
					Toast.makeText(MainActivity.this, "用戶名或密碼不能為空", Toast.LENGTH_LONG).show();
				}else {				
					new SendDateToServer(handler).SendDataToServer(name, pwd);
				}
			}
		});
	}

}

至此Android端項目已經完成了。下面就讓我們看一下APP運行效果吧:

Android運行效果圖:


通過GET方式傳遞數據給服務器——Android端運行效果圖2


二、關於通過GET方式傳遞數據給服務器時,中文亂碼的解決方案

當客戶端向服務器發送中文時服務器端會出現亂碼現象,如下圖:


vcq9tKu13cr9vt24+Lf+zvHG98qxo6zW0M7EwtLC67XEveK+9re9sLg=">


出現亂碼的原因主要是,Android客戶端我們采用的是UTF-8編碼,而Tomcat默認采用的是ISO8858-1編碼,所以會出現中文亂碼的現象。

解決方案有兩種:

第一種解決方案:

是使用UTF-8解碼請求參數得到漢字,然後再通過ISO8859-1進行編碼。此時服務器端的Servlet是:

package com.jph.sgm.servlet;

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

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

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//獲取請求的參數(使用utf-8進行解碼,然後用進行ISO8859-1編碼)
		String name=new String(request.getParameter("name").getBytes("ISO8859-1"),"utf-8");		
//		String name=request.getParameter("name");		
		String pwd=request.getParameter("pwd");
		System.out.println("name:"+name+"   pwd:"+pwd);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

運行結果如下圖:


UTF-8解碼請求參數得到漢字,然後再通過ISO8859-1進行編碼


第二種解決方案:

下面我們采用過濾器的方式來解決亂碼的問題:

第一步:建立一個Filter過濾器。

EncodingFilter.java

package com.jph.sgm.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

/**
 * Servlet Filter implementation class EncodingFilter
 */
@WebFilter("/*")
public class EncodingFilter implements Filter {

    /**
     * Default constructor. 
     */
    public EncodingFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req=(HttpServletRequest) request;
		if ("GET".equals(req.getMethod())) {
			HttpServletRequestEncodingWrapper wrapper=new HttpServletRequestEncodingWrapper(req);
			chain.doFilter(wrapper, response);
		}else {
			req.setCharacterEncoding("utf-8");
			chain.doFilter(request, response);
		}
	}
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}

上面的過濾器因為設置了過濾路徑為*/所以會過濾所有的Servlet。

在上面的過濾器中用到了一個包裝器,HttpServletRequestEncodingWrapper.java

package com.jph.sgm.filter;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class HttpServletRequestEncodingWrapper extends
		HttpServletRequestWrapper {
	private HttpServletRequest request;
	public HttpServletRequestEncodingWrapper(HttpServletRequest request) {
		// TODO Auto-generated constructor stub
		super(request);
		this.request=request;	
	}
	@Override
	public String getParameter(String name) {
		// TODO Auto-generated method stub
		String value=request.getParameter(name);
		if (value!=null) {
			try {//用utf-8進行解碼,然後用ISO8859-1進行編碼
				return new String(value.getBytes("ISO8859-1"),"utf-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return super.getParameter(name);
	}
}


重新運行項目可以看到服務器會將客戶端發來的數據用UTF-8進行解碼,用ISO8859-1進行編碼。運行效果圖如下:

采用過濾器的方式來解決亂碼的問題


Android網絡編程之傳遞數據給服務器(二)——通過POST的方式將數據傳遞給服務器

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved