標籤:通過get方式傳遞資料給伺服器 關於通過get方式傳遞資料給伺服器時中文 採用過濾器的方式來解決亂碼 android傳遞資料給伺服器
Android網路編程之傳遞資料給伺服器(一)
請尊重他人的勞動成果,轉載請註明出處:Android網路編程之傳遞資料給伺服器(一)
因為Android程式需要和伺服器進行通訊,所以需要伺服器端提供的支援。
一、通過GET方式傳遞資料給伺服器
通過GET方式上傳資料主要適用於資料大小不超過2KB,且對安全性要求不高的情況下。
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}}
第二步:測試Servlet
發布項目並在瀏覽器中輸入:http://localhost:8080/ServerForGETMethod/ServletForGETMethod?name=aa&pwd=124
可以再控制台看到如的輸出:
至此伺服器端項目已經完成。下面開始建立Android端項目。
2.建立Android端:
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 stubthis.handler=handler;}/** * 通過Get方式向伺服器發送資料 * @param name 使用者名稱 * @param pwd 密碼 */public void SendDataToServer(String name,String pwd) {// TODO Auto-generated method stubfinal Map<String, String>map=new HashMap<String, String>();map.put("name", name);map.put("pwd", pwd);new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubtry { if (sendGetRequest(map,url,"utf-8")) {handler.sendEmptyMessage(SEND_SUCCESS);//通知主線程資料發送成功}else {//將資料發送給伺服器失敗}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();}/** * 發送GET請求 * @param map 請求參數 * @param url 請求路徑 * @return * @throws Exception */private boolean sendGetRequest(Map<String, String> param, String url,String encoding) throws Exception {// TODO Auto-generated method stub//http://localhost:8080/ServerForGETMethod/ServletForGETMethod?name=aa&pwd=124StringBuffer sb=new StringBuffer(url);if (!url.equals("")&!param.isEmpty()) {sb.append("?");for (Map.Entry<String, String>entry: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");//佈建要求方式為GETif (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;}};};@Overrideprotected 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() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString 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運行:
2
二、關於通過GET方式傳遞資料給伺服器時,中文亂碼的解決方案
當用戶端向伺服器發送中文時伺服器端會出現亂碼現象,如:
出現亂碼的原因主要是,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}}
運行結果如:
第二種解決方案:
下面我們採用過濾器的方式來解決亂碼的問題:
第一步:建立一個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 stubHttpServletRequest 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 extendsHttpServletRequestWrapper {private HttpServletRequest request;public HttpServletRequestEncodingWrapper(HttpServletRequest request) {// TODO Auto-generated constructor stubsuper(request);this.request=request;}@Overridepublic String getParameter(String name) {// TODO Auto-generated method stubString 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 blocke.printStackTrace();}}return super.getParameter(name);}}
重新運行項目可以看到伺服器會將用戶端發來的資料用UTF-8進行解碼,用ISO8859-1進行編碼。運行如下:
Android網路編程之傳遞資料給伺服器(二)——通過POST的方式將資料傳遞給伺服器
Android網路編程之傳遞資料給伺服器(一)